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?
there are three ways
aButton.addActionListener(this);
in the case that class declarations contains implements ActionListener
and there is public void actionPerformed(ActionEvent ae) {
toof.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 classf.i. pseudocode
public class ButtonDemo {
aButton.addActionListener(new ButtonPress());
}
public class ButtonPress implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
}
}
f.i. pseudocode
aButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With