Java Reference
In-Depth Information
Menu1
Menu2
item 1
item 2
contentPane
Figure 8.1 The structure of an application with menus. The second menu is rolled out and
its entries can be selected
8.2
The view part
We need the following three Swing components to implement menus. First, a menu
bar realized by class JMenuBar . This is added to a frame between the title bar and
the content pane. Second, we need a menu realized by JMenu , which adds a menu
to the menu bar by displaying its title. Finally, we need menu items realized in
class JMenuItem , which defines the menu items on which the user can click. The
!
basic functions are automatically supplied: a menu rolls out if one clicks on the
title and it closes if one clicks somewhere else.
8.2.1
Menu bars
From JMenuBar we only need the constructor and the method to add a menu:
JMenuBar()
add(JMenu menu)
Menus are added to the menu bar from left to right in the order of the add com-
mands. To add a menu bar to a frame we use the following method from class
JFrame :
setJMenuBar(JMenuBar menuBar)
Note that there are distinct methods setJMenuBar and setMenuBar for adding a
JMenuBar (Swing) and a MenuBar (AWT).
8.2.2
Menus
From class JMenu we need the constructor which receives the menu title in a string
and methods to add menu items or separators (horizontal lines) to the menu:
JMenu(String menuTitle)
add(JMenuItem menuItem)
addSeparator()
Search WWH ::




Custom Search