Java Reference
In-Depth Information
Note Although technically possible, placing menus in locations where users wouldn't expect them to be
is poor user interface design.
In addition to being part of the basic class hierarchy, each of the selectable menu components
implements the MenuElement interface. The interface describes the menu behavior necessary to
support keyboard and mouse navigation. The predefined menu components already imple-
ment this behavior, so you don't have to. But if you're interested in how this interface works,
see the “MenuElement Interface” section later in this chapter.
Now let's take a look at the different Swing menu components.
JMenuBar Class
Swing's menu bar component is the JMenuBar . Its operation requires you to fill the menu bar
with JMenu elements that have JMenuItem elements. Then you add the menu bar to a JFrame or
some other user interface component requiring a menu bar. The menu bar then relies on the
assistance of a SingleSelectionModel to determine which JMenu to display or post after it's selected.
Creating JMenuBar Components
JMenuBar has a single constructor of the no-argument variety: public JMenuBar() . Once you
create the menu bar, you can add it to a window with the setJMenuBar() method of JApplet ,
JDialog , JFrame , JInternalFrame , or JRootPane . (Yes, even applets can have menu bars.)
JMenuBar menuBar = new JMenuBar();
// Add items to it
...
JFrame frame = new JFrame("MenuSample Example");
frame.setJMenuBar(menuBar);
With the system-provided look and feel types, the menu bar appears at the top of the
window, below any window title (if present), with setJMenuBar() . Other look and feel types, like
Aqua for the Macintosh, place the menu bar elsewhere.
You can also use the add() method of a Container to add a JMenuBar to a window. When
added with the add() method, a JMenuBar is arranged by the layout manager of the Container .
After you have a JMenuBar , the remaining menu classes all work together to fill the menu bar.
Adding Menus to and Removing Menus from Menu Bars
You need to add JMenu objects to a JMenuBar . Otherwise, the only thing displayed is the border
with nothing in it. There's a single method for adding menus to a JMenuBar :
public JMenu add(JMenu menu)
 
Search WWH ::




Custom Search