If your class implements an ActionListener or uses an anonymous ActionListener class object

What is the best way to implement the java.awt.event.ActionListener interface?

Ask your class to implement an ActionListener and add it as an ActionListener:

 class Foo implements ActionListener{ public Foo() { JButton button = new JButton(); button.addActionListener(this); } public void actionPerformed(ActionEvent e) { } } 

Or add an object of the anonymous ActionListener class:

 class Foo{ public Foo() { JButton button = new JButton(); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); } } 
+16
java swing actionlistener
Jul 11 2018-12-12T00:
source share
3 answers

Some (jeanette / kleopatra) say they almost never use an ActionListener and instead use Actions such as AbstractAction. It is almost always a bad ideal when your GUI class implements your listeners, although this violates the principle of shared responsibility and makes your code more difficult to maintain, and therefore I urge you not to.

So, for example, the inner class is used for this:

 import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.JButton; class Foo { public Foo() { JButton button = new JButton(new ButtonAction("Action", KeyEvent.VK_A)); } private class ButtonAction extends AbstractAction { public ButtonAction(String name, Integer mnemonic) { super(name); putValue(MNEMONIC_KEY, mnemonic); } @Override public void actionPerformed(ActionEvent e) { System.out.println("button pressed"); } } } 
+30
Jul 11 '12 at 17:24
source share

The second option (an anonymous class) is certainly better, the other option is to have a nested class inside Foo .

I would not go with the first option for two reasons:

  • Foo users do not need to know that it implements an ActionListener .
  • You cannot implement two different listeners in the same class.
+8
Jul 11 2018-12-12T00:
source share

It depends. If you want to reuse ActionListener for multiple components, the option is better. If the ActionListener is associated with only one button, option 2 is fine.

Generally, you should create a separate class (or inner class) if you expect some growth in the project. There is no need for Foo to implement ActionListener .

+4
Jul 11 2018-12-12T00:
source share



All Articles