Menu Bars and Menus
A top-level window can have a menu bar associated with it. A menu
bar displays a list of top-level menu choices. Each choice is associated with a
drop-down menu. This concept is implemented in the AWT by the following
classes: MenuBar, Menu, and MenuItem. In general, a menu bar contains one or more Menu objects. Each Menu object contains a list of MenuItem
objects. Each MenuItem object
represents something that can be selected by the user. Since Menu is a subclass of MenuItem, a hierarchy of nested
submenus can be created. It is also possible to include checkable menu items.
These are menu options of type CheckboxMenuItem
and will have a check mark next to them when they are selected.
To create a menu bar, first create an instance of MenuBar. This class defines only the
default constructor. Next, create instances of Menu that will define the selections displayed on the bar.
Following are the constructors for Menu:
Menu( ) throws HeadlessException
Menu(String optionName)
throws HeadlessException
Menu(String optionName,
boolean removable) throws
HeadlessException
Here, optionName
specifies the name of the menu selection. If removable is true, the
menu can be removed and allowed to float free. Otherwise, it will remain
attached to the menu bar. (Removable menus are implementation-dependent.) The
first form creates an empty menu.
Individual menu items are of type MenuItem. It defines these constructors:
MenuItem( ) throws HeadlessException MenuItem(String itemName) throws HeadlessException
MenuItem(String itemName,
MenuShortcut keyAccel) throws
HeadlessException
Here, itemName is the
name shown in the menu, and keyAccel
is the menu shortcut for this item.
You can disable or enable a menu item by using the setEnabled( ) method. Its form is shown
here:
void setEnabled(boolean enabledFlag)
If the argument enabledFlag
is true, the menu item is enabled.
If false, the menu item is disabled.
You can determine an item’s status by calling isEnabled( ). This method is shown here: boolean isEnabled( )
isEnabled( ) returns true if the menu item on which it is called is enabled. Otherwise,
it returns false.
You can change the name of a menu item by calling setLabel( ). You can retrieve the
current name by using getLabel( ). These
methods are as follows:
void setLabel(String newName)
String getLabel( )
Here, newName becomes the
new name of the invoking menu item. getLabel(
) returns the current name.
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 generate events only 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.*; /*
<applet
code="MenuDemo" width=250 height=250> </applet>
*/
//Create a subclass of Frame.
class
MenuFrame extends Frame { String msg = ""; CheckboxMenuItem debug,
test;
MenuFrame(String
title) { super(title);
//create menu bar and add it to frame
MenuBar mbar = new MenuBar(); setMenuBar(mbar);
//create the menu items
Menu
file = new Menu("File");
MenuItem
item1, item2, item3, item4, item5; file.add(item1 = new
MenuItem("New..."));
file.add(item2
= new MenuItem("Open...")); file.add(item3 = new
MenuItem("Close"));
file.add(item4
= new MenuItem("-")); file.add(item5 = new MenuItem("Quit..."));
mbar.add(file);
Menu
edit = new Menu("Edit"); MenuItem item6, item7, item8, item9;
edit.add(item6
= new MenuItem("Cut"));
edit.add(item7
= new MenuItem("Copy"));
edit.add(item8
= new MenuItem("Paste"));
edit.add(item9
= new MenuItem("-"));
Menu sub
= new Menu("Special"); MenuItem item10, item11, item12;
sub.add(item10 = new MenuItem("First")); sub.add(item11 = new
MenuItem("Second")); sub.add(item12 = new
MenuItem("Third")); edit.add(sub);
// these
are checkable menu items
debug =
new CheckboxMenuItem("Debug"); edit.add(debug);
test =
new CheckboxMenuItem("Testing"); edit.add(test);
mbar.add(edit);
create an object to handle action and item
events MyMenuHandler handler = new MyMenuHandler(this);
register it to receive those events item1.addActionListener(handler);
item2.addActionListener(handler); item3.addActionListener(handler);
item4.addActionListener(handler); item5.addActionListener(handler);
item6.addActionListener(handler); item7.addActionListener(handler);
item8.addActionListener(handler); item9.addActionListener(handler);
item10.addActionListener(handler); item11.addActionListener(handler);
item12.addActionListener(handler); debug.addItemListener(handler);
test.addItemListener(handler);
//create an object to handle window events
MyWindowAdapter adapter = new
MyWindowAdapter(this);
//register it to receive those events
addWindowListener(adapter);
}
public
void paint(Graphics g) { g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug
is on.", 10, 220); else
g.drawString("Debug
is off.", 10, 220);
if(test.getState())
g.drawString("Testing
is on.", 10, 240); else
g.drawString("Testing
is off.", 10, 240);
}
}
class
MyWindowAdapter extends WindowAdapter { MenuFrame menuFrame;
public
MyWindowAdapter(MenuFrame menuFrame) { this.menuFrame = menuFrame;
}
public
void windowClosing(WindowEvent we) { menuFrame.setVisible(false);
}
}
class
MyMenuHandler implements ActionListener, ItemListener { MenuFrame menuFrame;
public
MyMenuHandler(MenuFrame menuFrame) { this.menuFrame = menuFrame;
}
//
Handle action events.
public
void actionPerformed(ActionEvent ae) { String msg = "You selected ";
String
arg = ae.getActionCommand(); if(arg.equals("New..."))
msg +=
"New.";
else
if(arg.equals("Open...")) msg += "Open.";
else
if(arg.equals("Close")) msg += "Close.";
else
if(arg.equals("Quit...")) msg += "Quit.";
else
if(arg.equals("Edit")) msg += "Edit.";
else
if(arg.equals("Cut")) msg += "Cut.";
else
if(arg.equals("Copy")) msg += "Copy.";
else
if(arg.equals("Paste")) msg += "Paste.";
else
if(arg.equals("First")) msg += "First.";
else
if(arg.equals("Second")) msg += "Second.";
else
if(arg.equals("Third")) msg += "Third.";
else
if(arg.equals("Debug")) msg += "Debug.";
else
if(arg.equals("Testing")) msg += "Testing.";
menuFrame.msg
= msg; menuFrame.repaint();
}
//
Handle item events.
public
void itemStateChanged(ItemEvent ie) { menuFrame.repaint();
}
}
//
Create frame window.
public
class MenuDemo extends Applet { Frame f;
public
void init() {
f = new
MenuFrame("Menu Demo");
int
width = Integer.parseInt(getParameter("width")); int height =
Integer.parseInt(getParameter("height"));
setSize(new
Dimension(width, height));
f.setSize(width,
height); f.setVisible(true);
}
public
void start() { f.setVisible(true);
}
public
void stop() { f.setVisible(false);
}
}
Sample output from the MenuDemo
applet is shown in Figure 26-8.
There is one other menu-related class that you might find
interesting: PopupMenu. It works
just like Menu, but produces a menu
that can be displayed at a specific location. PopupMenu provides a flexible, useful alternative for some types of
menuing situations.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.