Java Reference
In-Depth Information
Class JMenuItem (a subclass of javax.swing.AbstractButton ) contains the methods
necessary to manage menu items . A menu item is a GUI component inside a menu that,
when selected, causes an action event. A menu item can be used to initiate an action, or it
can be a submenu that provides more menu items from which the user can select. Sub-
menus are useful for grouping related menu items in a menu.
Class JCheckBoxMenuItem (a subclass of javax.swing.JMenuItem ) contains the
methods necessary to manage menu items that can be toggled on or off. When a JCheck-
BoxMenuItem is selected, a check appears to the left of the menu item. When the JCheck-
BoxMenuItem is selected again, the check is removed.
Class JRadioButtonMenuItem (a subclass of javax.swing.JMenuItem ) contains the
methods necessary to manage menu items that can be toggled on or off like JCheckBox-
MenuItem s. When multiple JRadioButtonMenuItem s are maintained as part of a Button-
Group , only one item in the group can be selected at a given time. When a
JRadioButtonMenuItem is selected, a filled circle appears to the left of the menu item.
When another JRadioButtonMenuItem is selected, the filled circle of the previously
selected menu item is removed.
Using Menus in an Application
Figures 22.5-22.6 demonstrate various menu items and how to specify special characters
called mnemonics that can provide quick access to a menu or menu item from the key-
board. Mnemonics can be used with all subclasses of javax.swing.AbstractButton . Class
MenuFrame (Fig. 22.5) creates the GUI and handles the menu-item events. Most of the
code in this application appears in the class's constructor (lines 34-151).
1
// Fig. 22.5: MenuFrame.java
2
// Demonstrating menus.
3
import java.awt.Color;
4
import java.awt.Font;
5
import java.awt.BorderLayout;
6
import java.awt.event.ActionListener;
7
import java.awt.event.ActionEvent;
8
import java.awt.event.ItemListener;
9
import java.awt.event.ItemEvent;
10
import javax.swing.JFrame;
11
12
13
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JOptionPane;
14
import javax.swing.JLabel;
15
import javax.swing.SwingConstants;
16
import javax.swing.ButtonGroup;
17
18
19
20
21
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
public class MenuFrame extends JFrame
22
{
23
private final Color [] colorValues =
24
{ Color.BLACK , Color.BLUE , Color.RED , Color.GREEN };
Fig. 22.5 | JMenus and mnemonics. (Part 1 of 5.)
 
Search WWH ::




Custom Search