Java Reference
In-Depth Information
Menus
8
In this chapter we learn how to add menus to a frame and how to integrate them
into our application.
Menus are most often used as subcomponents of frames. They are hierarchically
organized. The topmost component is the menu bar . This is a rectangular area lo-
cated below the title bar of a frame and above the content pane. The intermediate
components are the menus .Amenu appears as text in the menu bar. When one
clicks on such a text the actual menu will roll out. It contains the menu items ,
which are lowest in the hierarchy. Figure 8.1 illustrates the structure. The menu
items are the components that trigger actions. They can be considered as a special
kind of button. In fact, like buttons, one uses an action listener to monitor them. It
sometimes is necessary to disable certain menu items for some of the time. A dis-
abled menu item does not trigger any action when clicked on. On most platforms
the text of a disabled menu item is shown lighter than that of enabled ones. One
situation where disabling a menu item makes sense is the following: assume data
are loaded from a file, and a menu item is then clicked on to start extensive calcu-
lations on the data. It would make no sense to repeat these extensive calculations
on the same data if the result is always the same. Thus one disables the menu item
that starts the calculations. It is enabled again only when new data are present.
We shall now implement a small GUI that demonstrates the use of menus in
Swing. As it does not handle any other data we do not implement a model part.
8.1
Specification of the GUI
The GUI consists of a frame with a label embedded into the content pane. It has
a menu bar with two menus entitled 'Menu 1' and 'Menu 2'. The first has three
items entitled 'Item 1', 'Test' and 'Exit'. The second menu has two items entitled
'Enable Test' and 'Disable Test'. Initially all items are enabled.
When a menu item is selected, the label displays a text 'Item XXXX selected'.
The two items in the second menu do something in addition. Whenever 'Disable
Test' is clicked on, the item 'Test' in the first menu is disabled; if it was disabled
before, nothing changes. Whenever 'Enable Test' is clicked on, the item 'Test' in
the first menu is enabled; if it was enabled before, nothing changes.
Search WWH ::




Custom Search