Swing component listening on itself and inner classes

I just got bad feedback on the uni project and need some impartial clarification;

Can someone explain when I should use the (anonymous) inner classes of the listener against components that listen to themselves? (a vs b)

a)

public class myButton extends JButton { public myButton() { addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // handling code... } }); } } 

b)

 public class myButton extends JButton implements ActionListener { public myButton() { addActionListener(this); } public void actionPerformed(ActionEvent e) { // handle the event } } 

Thanks guys Mitch

+1
source share
4 answers

c)

 JButton myButton = new JButton(); myButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // handling code... } }); 
+4
source

In cases where you have several buttons with different behavior, it is more convenient to assign a separate anonymous class for each button, you can still implement an ActionListener in your class and process the event in accordance with the source code:

 void actionPerformed(ActionEvent e) { if (e.getSrouce() == button1) { ... } else if (e.getSource() == button2) { ... } // ... } 
+3
source

I think this may be a personal preference. In any case, I will always deal with inner classes as a way to share responsibility and code organization.

In particular, this is the only way to use adapter classes (empty classes that already implement some specific Listener interfaces, so you only need to overwrite the methods you need and you don't need to provide an empty implementation of the ones you don't need).

+1
source

The fact is that when you declare your class myButton to implement ActionListener , you increase its visible API (i.e., add a new public method actionPerformed() , freely called by any code that contains a link to myButton ).

Since you probably don't want the " actionPerformed " to be part of the myButton API, you should use an inner class that will keep the open myButton API.

Note that Swing classes are full of bad examples, such as those where public methods are explicitly commented as โ€œimplementation details, do not call directly,โ€ is actually a very poor design decision.

+1
source

All Articles