Java Reference
In-Depth Information
Display 17.16
Listeners as Inner Classes
(part 2 of 2)
40 bluePanel =
new
JPanel();
41 greenPanel.setBackground(Color.LIGHT_GRAY);
42 add(bluePanel);
43 whitePanel =
new
JPanel();
44 whitePanel.setBackground(Color.LIGHT_GRAY);
45 add(whitePanel);
46 grayPanel =
new
JPanel();
47 grayPanel.setBackground(Color.LIGHT_GRAY);
48 add(grayPanel);
49 JMenu colorMenu =
new
JMenu("Add Colors");
50 JMenuItem blueChoice =
new
JMenuItem("Blue");
51 blueChoice.addActionListener(new blueListener());
52 colorMenu.add(blueChoice);
53 JMenuItem whiteChoice =
new
JMenuItem("White");
54 whiteChoice.addActionListener(new WhiteListener());
55 colorMenu.add(whiteChoice);
56 JMenuItem grayChoice =
new
JMenuItem("Gray");
57 grayChoice.addActionListener(new grayListener());
58 colorMenu.add(grayChoice);
59 JMenuBar bar =
new
JMenuBar();
60 bar.add(colorMenu);
61 setJMenuBar(bar);
62 }
63 }
Self-Test Exercises
25. What type of event is fired when you click a
JMenuItem?
How does it differ
from the type of event fired when you click a
JButton
?
26. Write code to create a
JButton
with
"Hello"
written on it but with
"Bye"
as
its action command.
27. Write code to create a
JMenuItem
with
"Hello"
as its displayed text (when it is
a choice in a menu) but with
"Bye"
as its action command.