How to add an ActionListener to a JButton

By Alvin J. Alexander, devdaily.com

Here's another one of those postings that's just here to help my bad memory. I currently travel a fair amount, work on different systems and projects, and can't remember the Java/Swing syntax for adding an ActionListener to a JButton, so here's a little sample code to help me remember:

myButton.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    // handle action here
  } 
});

Of course this assumes that I already have a JButton named myButton, and I want to add an ActionListener to that button, and of course implement an actionPerformed method. There are other ways to implement a listener, but this is my preferred approach.


devdaily logo