Java Reference
In-Depth Information
Notice a couple of characteristics of these listener objects:
We don't bother storing them in variables—so, in effect, they are anonymous objects. Only
the menu items have a reference to the listener objects, so that they can call their action-
Performed methods.
We only create a single object from each of the inner classes, because each is highly
specialized for a particular menu item.
These characteristics will lead us to explore a further feature of Java in the next section.
Exercise 11.11 Implement menu-item handling with inner classes, as discussed here, in
your own version of the image viewer.
Inner classes can generally be used in some cases to improve cohesion in larger projects. The foxes-
and-rabbits project from Chapter 10, for example, has a class SimulatorView that includes an
inner class FieldView . You may like to study this example to deepen your understanding.
Anonymous inner classes
The solution to the action dispatch problem using inner classes is fairly good, but we want
to take it one step further: we can use anonymous inner classes. The project imageviewer0-3
shows an implementation using this construct.
Exercise 11.12 Open the imageviewer0-3 project and examine it; that is, test it and read
its source code. Don't worry about understanding everything, because some new features
are the subject of this section. What do you notice about the use of inner classes to enable
ImageViewer to listen for and handle events?
Exercise 11.13 You will notice that activating the Quit menu item now quits the program.
Examine how this is done. Look up the library documentation for any classes and methods involved.
At the center of the changes in this version is the way the action listeners are set up to listen to
menu-item action events. The relevant code looks like this:
JMenuItem openItem = new JMenuItem("Open");
openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { openFile(); }
This code fragment looks quite mysterious when you encounter it for the first time, and you
will probably have trouble interpreting it, even if you have understood everything we have dis-
cussed in this topic so far. This construct is probably syntactically the most confusing example
that you will ever see in the Java language. But don't worry—we shall investigate this slowly.
What you are seeing here is an anonymous inner class. The idea for this construct is based on
the observations from our previous version that we only use each inner class exactly once to
create a single, unnamed instance. For this situation, anonymous inner classes provide a syntac-
tical shortcut: they let us define a class and create a single instance of this class, all in one step.
Search WWH ::

Custom Search