I just started getting my head around Java itself and Java Swing and I have some problems understanding the “Action Listener” concept. People say that C# and Java is very alike, but that’s another story when you actually try out both of them and compare.
I have the following auto-generated Action Listener for a button:
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
lblNylabel.setText("New label text");
}
});
I understand it like this:
- You call a non-static method via the object “btnNewButton” btnNewButton.addActionListener()
- The method takes one ActionListener instance as an argument
- The automated code instansiates an ActionListener instance via the “new ActionListener()” constructor call – What I don’t understand is that I can’t instansiate the ActionListener class myself, but it’s possible as an argument in the method call??
- A “actionPerformed” method is generated inside the new instance body and used here (What?)
- Inside the “actionPerformed” method you define what to do, when the button is clicked – Makes perfectly sense
Is it possible to do this in a more understanding/simple way that could help me understand the ActionListener concept?
When you do
You’re actually creating an instance of an anonymous subclass of
ActionListener.It is semantically equivalent of doing
(And tada, as a bonus, you just learned that you can have method local classes in Java 😉
Here are a few common alternatives:
Use an separate ordinary class:
(only possible if the other class has access to the required variables.)
Same as above, but with an inner (non-static) class:
(Here
lblNylabelwill probably be in scope for the inner class.)Let the enclosing class itself implement the
ActionListenerand usethisas argument toaddActionListener: