Reputation: 89
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);
}
}
Upvotes: 0
Views: 9754
Reputation: 299
public NewJFrame() {
initComponents();
jLabel1.setVisible(false);
}
private void initComponents(){
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setVisible(true);
}
This piece of code worked for me, Here NewJFrame()
is the constructor
Upvotes: 0
Reputation: 2047
Add ActionListener to your button:
wButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute when button is pressed
wLabel.setVisible(true);
}
});
Or better practice (I think) is to create separate class that implements ActionListener. But result will be the same. I don't know how big your application is, but I suggest to separate ActionListeners (like separate class I mentioned), just to make your code clear.
Upvotes: 0
Reputation: 15708
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);
}
}
Upvotes: 1