Java Reference
In-Depth Information
Listeners as Inner Classes
★
In all of our previous examples, our GUIs had only one action listener object to deal
with all action events from all buttons and menus in the GUI. The opposite extreme also
has much to recommend it. You can have a separate
ActionListener
class for each but-
ton or menu item, so that each button or menu item has its own unique action listener.
There is then no need for a multiway
if-else
statement. The listener knows which but-
ton or menu item was clicked because it listens to only one button or menu item.
The approach outlined in the previous paragraph does have one down side: You
typically need to give a lot of definitions of
ActionListener
classes. Rather than put-
ting each of these classes in a separate file, it is much cleaner to make them private
inner classes. This has the added advantage of allowing the
ActionListener
classes to
have access to private instance variables and methods of the outer class.
In Display 17.16 we have redone the GUI in Display 17.14 using the techniques of
this subsection.
Display 17.16
Listeners as Inner Classes
(part 1 of 3)
<
Import statements are the same as in Display 17.14.
>
1
public class
InnerListenersDemo
extends
JFrame
2{
3
public static final int
WIDTH = 300;
4
public static final int
HEIGHT = 200;
5
private
JPanel greenPanel;
6
private
JPanel whitePanel;
7
private
JPanel grayPanel;
8
private class
greenListener
implements
ActionListener
9
{
10
public void
actionPerformed(ActionEvent e)
11
{
12
greenPanel.setBackground(Color.GREEN);
13
}
14
}
//End of greenListener inner class
15
private class
WhiteListener
implements
ActionListener
16
{
17
public void
actionPerformed(ActionEvent e)
18
{
19
whitePanel.setBackground(Color.WHITE);
20
}
21
}
//End of WhiteListener inner class
(continued)