Java Reference
In-Depth Information
Anonymous inner classes are inner classes that don't have a name. Instead, an instance
of the class is simply generated “on the fly” as needed. Anonymous inner classes make im-
plementing some types of event handlers much easier. For example, given a JButton called
jbtn , you could implement an action listener for it like this:
Here, an anonymous inner class is created that implements the ActionListener interface.
Pay special attention to the syntax. The body of the inner class begins after the { that fol-
lows new ActionListener( ) . Also notice that the call to addActionListener( ) ends with a
) and a ; just like normal. The same basic syntax and approach is used to create an anonym-
ous inner class for any event handler. Of course, for different events, you specify different
event listeners and implement different methods.
One advantage to using an anonymous inner class is that the component that invokes
the class' methods is already known. For instance, in the preceding example, there is no
need to call getActionCommand( ) to determine what component generated the event, be-
cause this implementation of actionPerformed( ) will only be called by events generated
by jbtn . You will see anonymous inner classes at work in the Swing applet shown in the
following section.
In the case of an event whose listener defines a functional interface, you can handle the
event by use of a lambda expression. For example, action events can be handled with a
lambda expression because ActionListener defines only one abstract method, actionPer-
formed( ) . Using a lambda expression to implement ActionListener provides a compact
alternative to explicitly declaring an anonymous inner class. For example, again assuming
a JButton called jbtn , you could implement the action listener like this:
As was the case with the anonymous inner class approach, the object that generates the
event is known. In this case, the lambda expression applies only to the jbtn button.
Of course, in cases in which an event can be handled by use of a single expression, it
is not necessary to use a block lambda. For example, here is an action event handler for
Search WWH ::




Custom Search