Java Reference
In-Depth Information
Lines 59-72 create menu item
exitItem
, set its mnemonic to
x
, add it to
fileMenu
and register an
ActionListener
that terminates the program when the user selects
exit-
Item
. Lines 74-76 create the
JMenuBar
, attach it to the window with
JFrame
method
set-
JMenuBar
and use
JMenuBar
method
add
to attach the
fileMenu
to the
JMenuBar
.
Look-and-Feel Observation 22.4
Menus appear left to right in the order they're added to a
JMenuBar
.
Setting Up the
Format
Menu
Lines 78-79 create the
formatMenu
and set its mnemonic to
r
.
F
is not used because that's
the
File
menu's mnemonic. Lines 84-85 create
colorMenu
(this will be a submenu in
Format
)
and set its mnemonic to
C
. Line 88 creates
JRadioButtonMenuItem
array
colorItems
, which
refers to the menu items in
colorMenu
. Line 89 creates
ButtonGroup
colorButtonGroup
,
which ensures that only one of the
Color
submenu items is selected at a time. Line 90 creates
an instance of inner class
ItemHandler
(declared at lines 154-181) that responds to selec-
tions from the
Color
and
Font
submenus (discussed shortly). The loop at lines 93-100 creates
each
JRadioButtonMenuItem
in array
colorItems
, adds each menu item to
colorMenu
and
to
colorButtonGroup
and registers the
ActionListener
for each menu item.
Line 102 invokes
AbstractButton
method
setSelected
to select the first element in
array
colorItems
. Line 104 adds
colorMenu
as a submenu of
formatMenu
. Line 105
invokes
JMenu
method
addSeparator
to add a horizontal
separator
line to the menu.
Look-and-Feel Observation 22.5
A submenu is created by adding a menu as a menu item in another menu.
Look-and-Feel Observation 22.6
Separators can be added to a menu to group menu items logically.
Look-and-Feel Observation 22.7
Any
JComponent
can be added to a
JMenu
or to a
JMenuBar
.
Lines 108-126 create the
Font
submenu and several
JRadioButtonMenuItem
s and select
the first element of
JRadioButtonMenuItem
array
fonts
. Line 129 creates a
JCheckBoxMenu-
Item
array to represent the menu items for specifying bold and italic styles for the fonts. Line
130 creates an instance of inner class
StyleHandler
(declared at lines 185-208) to respond
to the
JCheckBoxMenuItem
events. The
for
statement at lines 133-139 creates each
JCheck-
BoxMenuItem
, adds it to
fontMenu
and registers its
ItemListener
. Line 141 adds
fontMenu
as a submenu of
formatMenu
. Line 142 adds the
formatMenu
to
bar
(the menu bar).
Creating the Rest of the GUI and Defining the Event Handlers
Lines 145-147 create a
JLabel
for which the
Format
menu items control the font, font
color and font style. The initial foreground color is set to the first element of array
color-
Values
(
Color.BLACK
) by invoking
JComponent
method
setForeground
. The initial font
is set to
Serif
with
PLAIN
style and
72
-point size. Line 149 sets the background color of