You can create a checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem. It has these constructors:
CheckboxMenuItem( ) throws HeadlessException
CheckboxMenuItem(String itemName) throws HeadlessException
CheckboxMenuItem(String itemName, boolean on) throws HeadlessException
Here, itemName is the name shown in the menu. Checkable items operate as toggles. Each
time one is selected, its state changes. In the first two forms, the checkable entry is unchecked.
In the third form, if on is true, the checkable entry is initially checked. Otherwise, it is cleared.
You can obtain the status of a checkable item by calling getState( ). You can set it to a
known state by using setState( ). These methods are shown here:
boolean getState( )
void setState(boolean checked)
If the item is checked, getState( ) returns true. Otherwise, it returns false. To check an item,
pass true to setState( ). To clear an item, pass false.
Once you have created a menu item, you must add the item to a Menu object by using
add( ), which has the following general form:
MenuItem add(MenuItem item)
Here, item is the item being added. Items are added to a menu in the order in which the calls
to add( ) take place. The item is returned.
Once you have added all items to a Menu object, you can add that object to the menu
bar by using this version of add( ) defined by MenuBar:
Menu add(Menu menu)
Here, menu is the menu being added. The menu is returned.
Menus only generate events when an item of type MenuItem or CheckboxMenuItem is
selected. They do not generate events when a menu bar is accessed to display a drop-down
menu, for example. Each time a menu item is selected, an ActionEvent object is generated.
By default, the action command string is the name of the menu item. However, you can
specify a different action command string by calling setActionCommand( ) on the menu
item. Each time a check box menu item is checked or unchecked, an ItemEvent object is
generated. Thus, you must implement the ActionListener and/or ItemListener interfaces
in order to handle these menu events.
The getItem( ) method of ItemEvent returns a reference to the item that generated this
event. The general form of this method is shown here:
Object getItem( )
Following is an example that adds a series of nested menus to a pop-up window. The
item selected is displayed in the window. The state of the two check box menu items is also
displayed.
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home