1

I am new to Java. I am trying to make text appear on a JLabel after a virtual button is clicked. However, I can't seem to find a solution to this. When I use the if statement it won't work. How can I make the text appear after the button was pressed?

import java.awt.event.*;  
import javax.swing.JFrame;  
import javax.swing.JLabel;  
import javax.swing.JButton;  
import javax.swing.JPanel;  
import java.awt.Graphics;  

public class autos extends JLabel implements ActionListener  
{
    private static final long serialVersionUID = 1L;  
    int now=0;
    public autos(){
        JLabel l=new JLabel("");
        JFrame f=new JFrame("the title");
        JPanel p=new JPanel();
        JButton b=new JButton("click");
        f.setBounds(400,500,400,500);
        f.setVisible(true);
        p.add(b);
        f.add(p);
        b.addActionListener(this);
        p.setVisible(true);
        p.add(l);
        f.add(l);
        if(now==1)
        {
            l.setText("hello");
            l.setOpaque(true);
        }
        p.setBounds(200,200,200,200);
        l.setBounds(100,100,100,100);
        l.setOpaque(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawRect(200,300,89,90);
        g.drawString("buv",80,80);
        repaint();
    }
    public static void main(String[] args)
    {
        new autos();    
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        now=1;
        System.out.println("worked");
        System.out.println(now);
    }
} 
mergenchik
  • 1,129
  • 16
  • 27
Daniel Tork
  • 113
  • 10

2 Answers2

2

You are setting up your label in your constructor code, which executes before the event handler which sets the now variable to 1.

What you can do is to move this code:

 l.setText("hello");
 l.setOpaque(true);

To here:

@Override
public void actionPerformed(ActionEvent e) {
    now=1;
    System.out.println("worked");
    System.out.println(now);

    l.setText("hello");
    l.setOpaque(true);    
}
npinti
  • 51,780
  • 5
  • 72
  • 96
  • 1
    @DanielTork: Move the decleration of `l` from outside the constructor and set it up as a global variable. Alternatively, you can declare the label and add it to its parent component directly within the code above. – npinti Oct 05 '15 at 09:21
  • @DanielTork Leave the code for initializing the JLabel in your constructor and add the JLabel as a instance variable/field. – Isuru Pathirana Oct 05 '15 at 09:21
1

This is a minimally working example of updating the text on button click. See the comments in code for the variety of changes.

import java.awt.event.*;
import javax.swing.*;

/* There is no need to extend label here. */
// public class autos extends JLabel implements ActionListener 
public class autos implements ActionListener {

    private static final long serialVersionUID = 1L;
    int now = 0;
    // this is now a class attribute, accessible to any method of this class.
    JLabel l;

    public autos() {
        // this no longer declares a local variable, but instead
        // creates an instance of the class attribute.
        l = new JLabel("");
        JFrame f = new JFrame("the title");
        JPanel p = new JPanel();
        JButton b = new JButton("click");
        f.setBounds(400, 500, 400, 500); // this needs fixing!
        f.setVisible(true);
        p.add(b);
        f.add(p);
        b.addActionListener(this);
        p.setVisible(true);
        p.add(l);
        f.add(l);
        p.setBounds(200, 200, 200, 200); // this needs fixing!
        l.setBounds(100, 100, 100, 100); // this needs fixing!
        l.setOpaque(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }
    /* I cannot tell what this was trying to achieve, but whatever it was,
    this was the wrong way to go about it.  Never call repaint() from within 
    the paintComponent method as this creates an infinite loop! */
    /*
     public void paintComponent(Graphics g) {
     super.paintComponent(g);
     g.drawRect(200, 300, 89, 90);
     g.drawString("buv", 80, 80);
     repaint();
     }
     */

    public static void main(String[] args) {
        // Swing GUIs should be created and updated on the EDT
        new autos();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        /* This logic is questionable, but it denpends on what you are trying
        to achieve here, something I'm not clear on. */
        now = 1;
        if (now == 1) {
            l.setText("hello");
            l.setOpaque(true);
        }
        System.out.println("worked");
        System.out.println(now);
    }
}

Edit

You added two comments at the setBounds part saying this needs fixing!. There I tried to resize the JPanel and JLabel but it's obvious it doesn't work.
How should I proceed here?

Here are some 'copy/paste comments' I regularly use:

  1. Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
  2. See Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (Yes.)
  3. Provide ASCII art or a simple drawing of the intended layout of the GUI at minimum size, and if resizable, with more width and height.

Now, to expand on those comments for this use-case:

  1. That is advice I offer for people trying to make a null layout, but it also applies here.
  2. This is relevant because there is one component (the custom painted one, if it exists) that needs to @Override the getPreferredSize(..) method to return a size as a suggestion to the layout managers or for packing the top level container.
  3. The 3rd comment is because it is hard to advise how to code this GUI without knowing the end effect that is required.

Of course, I should point out: Each SO thread is expected to be a single, specific question. I really should have told you to start a new question on the other matters, but let it slide for this edit.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • You added two comments at the "setBounds" part saying " this needs fixing!".There I tried to resize the JPanel and JLabel but it's obvious it doesn't work.How should I proceed here? – Daniel Tork Oct 05 '15 at 10:57