So I've stumbled across several ways of implementing an ActionListener and I'm wondering if someone can walk me through the differences of how each works and whether there are reasons or advantages to use one over the other?
The first is below in a block of code:
public void actionPerformed(ActionEvent arg0) {
// CODE HERE
}
The second way I saw was within another block of code as:
private class myListener implements ActionListener {
// CODE HERE
}
The third was is simply having a separate class for the ActionListener, with similar code to that above, but within a separate class.
I'm wondering whether the method approach is more efficient as new objects don't have to be created for each, you simply reference this
as the ActionListener rather than, for example, referencing new myListener()
. Thank you.
There's no difference in speed in any of the options; you'll always have an object that implements the ActionListener interface. Avoiding an instance of a separate class will just save you a few bytes of memory.
Your choice really should be based on what makes sense for your code, structurally. For example, having your public class implement ActionListener may look weird for those who are using that class, especially if the ActionListener behavior is supposed to be private to the class and not used outside it.
So it's mostly a choice of what you think looks better in your code; the only real difference will be with regards to field / method access (e.g. a separate, non-inner class won't have access to private methods and fields of your class, an anonymous inner class can't access non-final variables of the enclosing method, etc).
I don't like or use "implements ActionListener".
I do like and use anonymous inner classes like:
btnPurplescreen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color baseColor = Color.BLUE;
panelImage.setBackground(baseColor);
panelReference.setBackground(baseColor);
panelReference2.setBackground(baseColor);
baseType = BaseType.PURPLE;
}
});
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