Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To attach an ActionListener to a JButton in Java, follow these steps:

  1. Create a new JButton instance.
  2. Create a new ActionListener instance.
  3. Attach the ActionListener to the JButton using the addActionListener() method.

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.