在Java swing中单击Button后显示标签

时间:2014-09-19 10:33:12

标签: java eclipse swing jbutton jlabel

我想在点击按钮时显示标签。我正在使用Eclipse Juno。我添加了标签并设置了可见部分......

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);

按钮

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);

这是actionPerformed。我已经实现了ActionListener

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

    }
}

3 个答案:

答案 0 :(得分:0)

最初,您可以将标签的可见性设置为false,并在点击按钮后设置label.setVisible(true)

等可见性

例如像这样,请注意我正在使用lamba语法为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);
    }
}

答案 1 :(得分:0)

将ActionListener添加到按钮:

wButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         //Execute when button is pressed
         wLabel.setVisible(true);
    }
});

或者更好的练习(我认为)是创建实现ActionListener的单独类。但结果将是一样的。我不知道你的应用程序有多大,但我建议将ActionListeners分开(就像我提到的单独的类一样),只是为了让你的代码清晰。

答案 2 :(得分:0)

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);
}  

这段代码对我有用,这里NewJFrame()是构造函数