The JMenuBar Class

Swing’s JMenuBar class supersedes the older AWT MenuBar class. This class creates a horizontal menubar component with zero or more menus attached to it. JMenuBar uses the DefaultSingleSelectionModel as its data model; this is because the user can raise, or activate, only one of its menus at a given time. Once the mouse pointer leaves that menu, the class removes the menu from the screen (or cancels it, in Swing lingo), and all menus again become eligible to be raised. Figure 14.4 shows the class hierarchy for the JMenuBar component.

A sample of Swing menu effects

Figure 14-4. A sample of Swing menu effects

You can add JMenu objects from the menubar with the add() method of the JMenuBar class. JMenuBar then assigns an integer index based on the order in which the menus were added. The menubar displays the menus from left to right on the bar according to their assigned index. There is one exception: the help menu. You are allowed to mark one menu as the help menu; the location of the help menu is up to the look-and-feel.

Note

As of JDK 1.2 beta 4, the help menu feature was not implemented.

Menubar Placement

You can attach menubars to Swing frames or applets in one of two ways. First, you can use the setJMenuBar() method of JFrame, JDialog, JApplet, or JInternalFrame:

JFrame frame = new JFrame("Menu"); JMenuBar menuBar = new JMenuBar(); // Attach the menu bar to the frame frame.setJMenuBar(menuBar); ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.