Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax of adding an action listener

When I enter the following code:

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

my IDE (NetBeans) highlights this as a leaking this statement. Though there never seem to be any negative repercussions from using the statement as such, some docs that I have read indicate that the more proper method is to add the action listener as a new instance of an inner class that implements ActionListener. What do NetBeans and these docs know that I don't? What is really meant by a leaking this statement? Are there negative repercussions that I am unaware of in the use of this in this way?

like image 408
Jeremy Johnson Avatar asked Mar 23 '23 21:03

Jeremy Johnson


2 Answers

there are three ways

  • aButton.addActionListener(this); in the case that class declarations contains implements ActionListener and there is public void actionPerformed(ActionEvent ae) { too

f.i. pseudocode

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 in the case that ActionLIstener is declared as separate class

f.i. pseudocode

public class ButtonDemo {    
     aButton.addActionListener(new ButtonPress());
}

public class ButtonPress implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}
  • simpler, clear and without side effects (a.m. two ways) is to create inner anonymous listener

f.i. pseudocode

    aButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

        }
    });
like image 70
mKorbel Avatar answered Mar 27 '23 17:03

mKorbel


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

If you use other classes, then you can use ActionListeners that are implemented elsewhere, or reuse ones that were designed for a specific common purpose, or define e.g. anonymous inner classes inline which may be convenient in your situation. This is also perfectly 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 whatever makes the most sense for your situation and provides the clearest, most maintainable, properly functioning code. Have common sense, be familiar with the language you are working in and the options available, make sane judgments. A language is a way to express an idea, speak (type) clearly.

like image 20
Jason C Avatar answered Mar 27 '23 19:03

Jason C