We usually discuss this sort of thing in our GUIs forum; this
thread will eventually migrate thither.
I have a rule of thumb about Listeners:-
1: If a Listener does something generic which might be useful elsewhere: public top‑level class. I couldn't find such a top‑level class, but I did find this, which you can doubtless complete easily enough. No, I have found a more complete version here, but it appears only to work on 1st April.2: If a Listener is used several times for similar things, make it a private inner class.3: If it is used in one place and nowhere else and there is nothing else similar, I would in the past have said use an anonymous class.Of course nowadays in Java8 you can often use a λ expression instead:-
If you look at the ActionListener interface, you find it is a functional interface; even though it is not annotated with
@FunctionalInterface,
ActionListener has only one abstract method (in fact it only has one method at all), so it counts as a functional interface. That means the compiler can create an instance without needing the whole class written out. You need the method parameters, the arrow token, and the method body, and the javac tool can work out what to do:-
can be shortened by leaving out the method name and replacing the {} with ->
Now the compiler can usually infer the type of the parameter, so you can omit that.
If you only have one token in the () left of ->, you can miss out the ()
Now you have reduced about ten lines of code to that.
Similarly you can often replace an anonymous class by a λ:-
Read about inner classes in the
Java™ Tutorials.