How to create on click event for buttons in swing?

旧时模样 提交于 2020-01-23 07:44:33

问题


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 ?


回答1:


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

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




回答2:


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

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


来源:https://stackoverflow.com/questions/21879243/how-to-create-on-click-event-for-buttons-in-swing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!