Java Reference
In-Depth Information
Instances of the inner class are attached to instances of the enclosing class; they can only exist
together with an enclosing instance, and they exist conceptually inside the enclosing instance.
One interesting detail is that statements in methods of the inner class can see and access private
fields and methods of the enclosing class. There is obviously a very tight coupling between the
two, therefore. The inner class is considered to be a part of the enclosing class just as are any of
the enclosing class's methods.
We can now use this construct to make a separate action-listener class for every menu item we
like to listen to. As they are separate classes, they can each have a separate actionPerformed
method so that each of these methods handles only a single item's activation. The structure is this:
class ImageViewer
{
...
class OpenActionListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// perform open action
}
}
class QuitActionListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// perform quit action
}
}
}
(As a style guide, we usually write inner classes at the end of the enclosing class—after the
methods.)
Once we have done this, we can now create instances of these inner classes in exactly the same way
as for those of any other class. Note also that ImageViewer does not implement ActionListener
anymore (we remove its actionPerformed method), but the two inner classes do. This now al-
lows us to use instances of the inner classes as action listeners for the menu items.
JMenuItem openItem = new JMenuItem("Open");
openItem.addActionListener(new OpenActionListener());
...
JMenuItem quitItem = new JMenuItem("Quit");
quitItem.addActionListener(new QuitActionListener());
In summary, instead of having the image-viewer object listen to all action events, we create
separate listener objects for each possible event, where each listener object listens to one sin-
gle event type. As every listener has its own actionPerformed method, we can now write
specific handling code in these methods. Also, because the listener classes are in the scope
of the enclosing class (they can access the enclosing class's private fields and methods), they
can make full use of the enclosing class in the implementation of the actionPerformed
methods.
 
Search WWH ::




Custom Search