如何在Swing中为按钮创建点击事件?

32

我的任务是在单击按钮时检索文本字段的值并在警告框中显示它。我如何为Java Swing中的按钮生成单击事件?

5个回答

64

为此,您需要使用ActionListener,例如:

JButton b = new JButton("push me");
b.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        //your actions
    }
});

要通过编程方式生成点击事件,可以使用JButtondoClick()方法:b.doClick();


actionPerformed 方法通常在按钮被点击时使用。如果您想要对按钮进行一些花哨的交互,您也可以使用 其他事件,例如 mousePressed 在 MouseListener 中。 - SebastianH
2
@Suresh 我知道你一直在使用GUI Builder。你需要做的是从设计视图中右键单击按钮,然后选择“事件->操作->actionPerformed”,然后你将在源代码中看到自动生成的代码。Alex +1 - Paul Samsotha

10

首先,使用一个按钮,为其分配一个ActionListener,在其中使用JOptionPane显示消息。

class MyWindow extends JFrame {

    public static void main(String[] args) {

        final JTextBox textBox = new JTextBox("some text here");
        JButton button = new JButton("Click!");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(this, textBox.getText());
            }
        });
    }
}

6
我不认为 JTextBox 是一个真正的类。这个不起作用... - data princess

7
你也可以使用lambda函数:
JButton button = new JButton("click me");
button.addActionListener(e ->
{
    // your code here
});

然而,如果你指的是 Qt 中的信号和槽机制,则 Swing 不支持此特性。但是你可以使用“观察者”模式(链接)自己实现。


0

public GUI() {

JButton btn1 = new JButton("点击我!");

add(btn1);

btn1.addActionListener(new ActionListener()) {

        @Override
        public void actionPerformed(ActionEvent e) {

            //action for the button
        }
    }

}


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

0
JButton jEightButton=new JButton();
    

jEightButton.addActionListener(this);

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    
    jframe.getContentPane().setBackground(Color.blue);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接