Syntax for adding an action listener

When I enter the following code:

JButton aButton = new JButton("Button"); aButtin.addActionListener(this); 

my IDE (NetBeans) emphasizes this as a leak of this statement. Although there have never been any negative consequences from using the instruction as such, some of the documents I read indicate that the more correct way is to add an action listener as a new instance of the inner class that implements the ActionListener. What do NetBeans and these documents know that I am not doing this? What does the leak of this statement really mean? Are there any negative consequences that I do not suspect of using this in this way?

+4
source share
3 answers

There are three ways:

  • aButton.addActionListener(this); if class declarations contain implements ActionListener , as well as public void actionPerformed(ActionEvent ae) {

fi pseudo code

 public class ButtonDemo implements ActionListener{ aButton.addActionListener(this); @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == aButton) { } } } 
  • aButton.addActionListener(new ButtonPress()); is that ActionLIstener is declared as a separate class

fi pseudo code

 public class ButtonDemo { aButton.addActionListener(new ButtonPress()); } public class ButtonPress implements ActionListener { @Override public void actionPerformed(ActionEvent e) { } } 
  • simpler, more understandable and without side effects (two ways) - create an internal anonymous listener

fi pseudo code

  aButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); 
+4
source

If you use this , in order for this process ActionEvents from multiple sources, you need to add logic to check the source or command line of the action. This is perfectly reasonable.

If you use other classes, you can use ActionListeners that are implemented elsewhere, or reuse those that were designed for a specific general purpose, or define, for example. Anonymous inner classes that may be convenient in your situation. It is also quite reasonable.

Do not think in terms of “advantages” or “disadvantages” - this is such a common mistake (is it “bad” to do xyz? Is xyz “good practice”?). You use what matters most to your situation and provides the clearest, most repaired, properly functioning code. Be common sense, be familiar with the language you work in, and the options available, make reasonable judgments. Language is a way of expressing an idea, clearly speaking (of type).

+2
source

I think one of the drawbacks of using an internal implementation of the class is that the listener cannot be reused for other buttons, in case they must have the same listener. Something like that:

Can you use the same OnClickListener for different buttons?

+1
source

Source: https://habr.com/ru/post/1495834/


All Articles