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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21879243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:13:49  来源:igfitidea点击:

How to create on click event for buttons in swing?

javaswingjbutton

提问by Suresh

My task is to retrieve a value of text field and display it in a alert box when clicking on the button. how to generate the on click event for button in java swing ?

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

回答by alex2410

For that, you need to use ActionListener, for example:

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

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

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

For generating click event programmatically, you can use doClick()method of JButton: b.doClick();

要以编程方式生成点击事件,您可以使用以下doClick()方法JButtonb.doClick();

回答by Shocked

First, use a button, assign an ActionListener to it, in which you use JOptionPane to show the message.

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