1 | initial version |
To attach an ActionListener to a JButton in Java, follow these steps:
Here's an example code snippet:
JButton myButton = new JButton("Click me!");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle button click event
}
});
In the above example, we create a new JButton instance called myButton
. We also create a new ActionListener instance using an anonymous inner class. The actionPerformed()
method is overridden to handle the button click event. Finally, we attach the ActionListener to the JButton using the addActionListener()
method.