Java Reference
In-Depth Information
By default, consecutively added menus are displayed from left to right. This makes the first
menu added the leftmost menu and the last menu added the rightmost menu. Menus added in
between are displayed in the order in which they're added. For instance, in the sample program
from Listing 6-1, the menus were added as follows:
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
menuBar.add(editMenu);
■
Note
Placing a
JMenuBar
in the
EAST
or
WEST
area of a
BorderLayout
does not make the menus
appear vertically, stacked one on top of another. You must customize the menu bar if you want menus to
appear this way. See Figure 6-4, later in this chapter, for one implementation of a top-down menu bar.
In addition to the
add()
method from
JMenuBar
, several overloaded varieties of the
add()
method inherited from
Container
offer more control over menu positioning. Of particular
interest is the
add(Component component, int index)
method, which allows you to specify the
position in which the new
JMenu
is to appear. Using this second variety of
add()
allows you to
place the
File
and
Edit JMenu
components in a
JMenuBar
in a different order, but with the
same results:
menuBar.add(editMenu);
menuBar.add(fileMenu, 0);
If you've added a
JMenu
component to a
JMenuBar
, you can remove it with either the
remove(Component component)
or
remove(int index)
method inherited from
Container
:
bar.remove(edit);
bar.remove(0);
■
Tip
Adding or removing menus from a menu bar is likely to confuse users. However, sometimes it's necessary
to do so—especially if you want to have an expert mode that enables a certain functionality that a nonexpert
mode hides. A better approach is to disable/enable individual menu items or entire menus. If you do add or
remove menus, you must then
revalidate()
the menu bar to display the changes.
JMenuBar Properties
Table 6-1 shows the 11 properties of
JMenuBar
. Half the properties are read-only, allowing you
only to query the current state of the menu bar. The remaining properties allow you to alter the
appearance of the menu bar by deciding whether the border of the menu bar is painted and
selecting the size of the margin between menu elements. The selected property and selection
model control which menu on the menu bar, if any, is currently selected. When the selected