如何为摇摆中的按钮创建点击事件?

时间:2014-02-19 11:34:16

标签: java swing jbutton

我的任务是检索文本字段的值,并在单击按钮时将其显示在警告框中。如何在java swing中为按钮生成on click事件?

3 个答案:

答案 0 :(得分:16)

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

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

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

要以编程方式生成点击事件,您可以使用JButton的{​​{3}}方法:b.doClick();

答案 1 :(得分:2)

首先,使用一个按钮,为其指定一个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());
            }
        });
    }
}

答案 2 :(得分:0)

您也可以使用 lambda 函数:

JButton button = new JButton("click me");
button.addActionListener(e ->
{
    // your code here
});

但是,如果您指的是 Qt 中的信号和槽,那么 Swing 不支持这一点。但您始终可以使用“观察者”模式 (link) 自己实现这一点。