How to create on click event for buttons in swing?

Suresh picture Suresh · Feb 19, 2014 · Viewed 66.5k times · Source

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?

Answer

alex2410 picture alex2410 · Feb 19, 2014

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