Java Reference
In-Depth Information
Display 17.14
A GUI with a Menu
(part 2 of 3)
34
grayPanel =
new
JPanel();
35
grayPanel.setBackground(Color.LIGHT_GRAY);
36
add(grayPanel);
37
JMenu colorMenu =
new
JMenu("Add Colors");
38
JMenuItem greenChoice =
new
JMenuItem("Green");
39
greenChoice.addActionListener(
this
);
40
colorMenu.add(greenChoice);
41
JMenuItem whiteChoice =
new
JMenuItem("White");
42
whiteChoice.addActionListener(
this
);
43
colorMenu.add(whiteChoice);
44
JMenuItem grayChoice =
new
JMenuItem("Gray");
45
grayChoice.addActionListener(
this
);
46
colorMenu.add(grayChoice);
47
JMenuBar bar =
new
JMenuBar();
48
bar.add(colorMenu);
49
setJMenuBar(bar);
50
}
The definition of
actionPerformed
is identical to the definition
given in Display 17.11 for a similar GUI using buttons instead of
menu items.
51
public void
actionPerformed(ActionEvent e)
52
{
53
String buttonString = e.getActionCommand();
54
if
(buttonString.equals("Green"))
55
greenPanel.setBackground(Color.GREEN);
56
else if
(buttonString.equals("White"))
57
whitePanel.setBackground(Color.WHITE);
58
else if
(buttonString.equals("Gray"))
59
grayPanel.setBackground(Color.GRAY);
60
else
61
System.out.println("Unexpected error.");
62
}
63
}
(continued)