Search code examples
javaeclipseswingjbuttonjlabel

display a label after the Button is clicked in Java swing


I want to display a label, when a button is clicked. I am using Eclipse Juno. I have the label added and setting the visible part...

wLabel = new JLabel("YOu and Me");
    wLabel .setVisible(false);
    wLabel .setBounds(80, 35, 100, 25);
    wLabel .setFont(new Font("Meiryo", Font.PLAIN, 9));
    wLabel .setForeground(new Color(255, 102, 21));
    add(wLabel);

the button

wButton = new JButton("W");
    wButton .setActionCommand("myButton");
    wButton .addActionListener(this);
    wButton .setFont(new Font("Meiryo UI", Font.PLAIN, 11));
    wButton .setBounds(10, 33, 70, 35);
    wButton .setBackground(new Color(102, 51, 20));
    add(wButton);

and here is the actionPerformed. I already implemented ActionListener

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getActionCommand().equals("myButton")) {
        wLabel.setVisible(true);

    }
}

Solution

  • Initially you can set the visibility to false of your label and after clicking the button set the visibility like label.setVisible(true)

    for e.g. like this, note i am using lamba syntax for java 8

    import java.awt.Dimension;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class BtnDisabled {
    
        public static void main(String[] args) {
    
            JFrame frame = new JFrame("");
            JLabel label = new JLabel("You and Me");
            label.setVisible(false);
            JPanel panel = new JPanel();
            panel.add(label);
    
            JButton btn = new JButton("W");
        btn.addActionListener(e -> {
            if (!label.isVisible()) {
                label.setVisible(true);
            }
        });
            panel.add(btn);
            frame.add(panel);
            frame.setSize(new Dimension(500, 500));
    
            frame.setVisible(true);
        }
    }