1

Hi I have a JButton that I want to program so that when pressed, a new JLabel is displayed on screen. I have added the JLabel to the frame and it is visible. It shows outside of actionPerformed but not inside it.

The label is declared as lbl outside the method and then it is created in the actionPerformed method

    public void actionPerformed(ActionEvent e) {

        JLabel lbl = new JLabel("ONE");
}

Can anybody help me to make the label appear when the button is pressed? Thanks

jj007
  • 43
  • 2
  • 9

3 Answers3

3

This is the way you do it:

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == buttonname){ 
        labelname.setVisible(true);

    }
}

Also, don't forget to do

buttonname.addActionListener(this);

and in your method where you layout the form add this:

yourPanel.Add(labelname)

Hope this helps!

Arno

1

You have also declared it inside the actionPerformed method - this declaration is perhaps hiding the earlier one (outside the method). Can you post more code? The following code works fine for me:

public class NewLabel
{
    public static void main(String[] args)
    {

        final JFrame frame = new JFrame();

        JButton button = new JButton("Add label");

        button.addActionListener(new ActionListener()
        {

            public void actionPerformed(ActionEvent e)
            {

                JLabel lbl = new JLabel("ONE");
                frame.add(lbl);

                frame.setSize(100, 100);
                // or you can't see the new button without resizing manually!
            }
        });

        frame.add(button);
        frame.pack();
        frame.setVisible(true);

    }
}

(In some cases you may also need to tell the container/frame to re-layout, by calling revalidate() on it...)

DNA
  • 42,007
  • 12
  • 107
  • 146
  • I am using a frame, not a container. I tried that code for the frame and it didnt work – jj007 Jan 29 '12 at 20:17
  • A JFrame _is_ a container. Well, a subclass of Container anyway. Have you tried calling frame.revalidate() and frame.repaint() after adding the JLabel? – DNA Jan 29 '12 at 20:18
  • The button is linked up fine, I can make it println etc just not create a label – jj007 Jan 29 '12 at 20:22
  • I have edited the code so it is a fully-working example rather than an example snippet (though I have omitted the imports). I have tested this and it works for me... – DNA Jan 29 '12 at 20:26
  • thanks for some reason I do the same yet it still doesnt work, I'll look into it. Thanks for the help – jj007 Jan 29 '12 at 20:43
1

You created the JLabel, but you did not add it to any container. That is why it is not showing. What you wrote is good, all you need is to add the label to the container it is supposed to be on.

JLabel lbl = new JLabel("ONE");
yourPanel.Add(lbl);
xtrem
  • 1,737
  • 12
  • 13