FileDocCategorySizeDatePackage
MenuItem.javaAPI DocJava SE 6 API29161Tue Jun 10 00:25:18 BST 2008java.awt

MenuItem

public class MenuItem extends MenuComponent implements Accessible
All items in a menu must belong to the class MenuItem, or one of its subclasses.

The default MenuItem object embodies a simple labeled menu item.

This picture of a menu bar shows five menu items: The following text describes this graphic.
The first two items are simple menu items, labeled "Basic" and "Simple". Following these two items is a separator, which is itself a menu item, created with the label "-". Next is an instance of CheckboxMenuItem labeled "Check". The final menu item is a submenu labeled "More Examples", and this submenu is an instance of Menu.

When a menu item is selected, AWT sends an action event to the menu item. Since the event is an instance of ActionEvent, the processEvent method examines the event and passes it along to processActionEvent. The latter method redirects the event to any ActionListener objects that have registered an interest in action events generated by this menu item.

Note that the subclass Menu overrides this behavior and does not send any event to the frame until one of its subitems is selected.

version
1.94, 07/11/06
author
Sami Shaio

Fields Summary
boolean
enabled
A value to indicate whether a menu item is enabled or not. If it is enabled, enabled will be set to true. Else enabled will be set to false.
String
label
label is the label of a menu item. It can be any string.
String
actionCommand
This field indicates the command tha has been issued by a particular menu item. By default the actionCommand is the label of the menu item, unless it has been set using setActionCommand.
long
eventMask
The eventMask is ONLY set by subclasses via enableEvents. The mask should NOT be set when listeners are registered so that we can distinguish the difference between when listeners request events and subclasses request them.
transient ActionListener
actionListener
private MenuShortcut
shortcut
A sequence of key stokes that ia associated with a menu item. Note :in 1.1.2 you must use setActionCommand() on a menu item in order for its shortcut to work.
private static final String
base
private static int
nameCounter
private static final long
serialVersionUID
private int
menuItemSerializedDataVersion
Menu item serialized data version.
Constructors Summary
public MenuItem()
Constructs a new MenuItem with an empty label and no keyboard shortcut.

exception
HeadlessException if GraphicsEnvironment.isHeadless() returns true.
see
java.awt.GraphicsEnvironment#isHeadless
since
JDK1.1


                                  
        
	this("", null);
    
public MenuItem(String label)
Constructs a new MenuItem with the specified label and no keyboard shortcut. Note that use of "-" in a label is reserved to indicate a separator between menu items. By default, all menu items except for separators are enabled.

param
label the label for this menu item.
exception
HeadlessException if GraphicsEnvironment.isHeadless() returns true.
see
java.awt.GraphicsEnvironment#isHeadless
since
JDK1.0

	this(label, null);
    
public MenuItem(String label, MenuShortcut s)
Create a menu item with an associated keyboard shortcut. Note that use of "-" in a label is reserved to indicate a separator between menu items. By default, all menu items except for separators are enabled.

param
label the label for this menu item.
param
s the instance of MenuShortcut associated with this menu item.
exception
HeadlessException if GraphicsEnvironment.isHeadless() returns true.
see
java.awt.GraphicsEnvironment#isHeadless
since
JDK1.1

	this.label = label;
        this.shortcut = s;
    
Methods Summary
public synchronized voidaddActionListener(java.awt.event.ActionListener l)
Adds the specified action listener to receive action events from this menu item. If l is null, no exception is thrown and no action is performed.

Refer to AWT Threading Issues for details on AWT's threading model.

param
l the action listener.
see
#removeActionListener
see
#getActionListeners
see
java.awt.event.ActionEvent
see
java.awt.event.ActionListener
since
JDK1.1

	if (l == null) {
	    return;
	}
	actionListener = AWTEventMulticaster.add(actionListener, l);
        newEventsOnly = true;
    
public voidaddNotify()
Creates the menu item's peer. The peer allows us to modify the appearance of the menu item without changing its functionality.

        synchronized (getTreeLock()) {
	    if (peer == null)
	        peer = Toolkit.getDefaultToolkit().createMenuItem(this);
	}
    
java.lang.StringconstructComponentName()
Construct a name for this MenuComponent. Called by getName() when the name is null.

        synchronized (getClass()) {
	    return base + nameCounter++;
	}
    
public voiddeleteShortcut()
Delete any MenuShortcut object associated with this menu item.

since
JDK1.1

        shortcut = null;
	MenuItemPeer peer = (MenuItemPeer)this.peer;
	if (peer != null) {
	    peer.setLabel(label);
	}
    
voiddeleteShortcut(java.awt.MenuShortcut s)

        if (s.equals(shortcut)) {
            shortcut = null;
            MenuItemPeer peer = (MenuItemPeer)this.peer;
            if (peer != null) {
                peer.setLabel(label);
            }
        }
    
public synchronized voiddisable()

deprecated
As of JDK version 1.1, replaced by setEnabled(boolean).

	enabled = false;
	MenuItemPeer peer = (MenuItemPeer)this.peer;
	if (peer != null) {
	    peer.disable();
	}
    
protected final voiddisableEvents(long eventsToDisable)
Disables event delivery to this menu item for events defined by the specified event mask parameter.

param
eventsToDisable the event mask defining the event types
see
java.awt.MenuItem#processEvent
see
java.awt.MenuItem#enableEvents
see
java.awt.Component#disableEvents
since
JDK1.1

        eventMask &= ~eventsToDisable;
    
voiddoMenuEvent(long when, int modifiers)

        Toolkit.getEventQueue().postEvent(
            new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
                            getActionCommand(), when, modifiers));
    
public synchronized voidenable()

deprecated
As of JDK version 1.1, replaced by setEnabled(boolean).

	enabled = true;
	MenuItemPeer peer = (MenuItemPeer)this.peer;
	if (peer != null) {
	    peer.enable();
	}
    
public voidenable(boolean b)

deprecated
As of JDK version 1.1, replaced by setEnabled(boolean).

    	if (b) {
	    enable();
	} else {
	    disable();
	}
    
protected final voidenableEvents(long eventsToEnable)
Enables event delivery to this menu item for events to be defined by the specified event mask parameter

Since event types are automatically enabled when a listener for that type is added to the menu item, this method only needs to be invoked by subclasses of MenuItem which desire to have the specified event types delivered to processEvent regardless of whether a listener is registered.

param
eventsToEnable the event mask defining the event types
see
java.awt.MenuItem#processEvent
see
java.awt.MenuItem#disableEvents
see
java.awt.Component#enableEvents
since
JDK1.1

        eventMask |= eventsToEnable;
	newEventsOnly = true;
    
booleaneventEnabled(java.awt.AWTEvent e)

        if (e.id == ActionEvent.ACTION_PERFORMED) {
            if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 ||
                actionListener != null) {
                return true;
            }
            return false;
        }
        return super.eventEnabled(e);
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this MenuItem. For menu items, the AccessibleContext takes the form of an AccessibleAWTMenuItem. A new AccessibleAWTMenuItem instance is created if necessary.

return
an AccessibleAWTMenuItem that serves as the AccessibleContext of this MenuItem
since
1.3

        if (accessibleContext == null) {
            accessibleContext = new AccessibleAWTMenuItem();
        }
        return accessibleContext;
    
public java.lang.StringgetActionCommand()
Gets the command name of the action event that is fired by this menu item.

see
java.awt.MenuItem#setActionCommand
since
JDK1.1

        return getActionCommandImpl();
    
final java.lang.StringgetActionCommandImpl()

        return (actionCommand == null? label : actionCommand);
    
public synchronized java.awt.event.ActionListener[]getActionListeners()
Returns an array of all the action listeners registered on this menu item.

return
all of this menu item's ActionListeners or an empty array if no action listeners are currently registered
see
#addActionListener
see
#removeActionListener
see
java.awt.event.ActionEvent
see
java.awt.event.ActionListener
since
1.4

        return (ActionListener[])(getListeners(ActionListener.class));
    
public java.lang.StringgetLabel()
Gets the label for this menu item.

return
the label of this menu item, or null if this menu item has no label.
see
java.awt.MenuItem#setLabel
since
JDK1.0

	return label;
    
public T[]getListeners(java.lang.Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this MenuItem. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a MenuItem m for its action listeners with the following code:

ActionListener[] als = (ActionListener[])(m.getListeners(ActionListener.class));
If no such listeners exist, this method returns an empty array.

param
listenerType the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
return
an array of all objects registered as FooListeners on this menu item, or an empty array if no such listeners have been added
exception
ClassCastException if listenerType doesn't specify a class or interface that implements java.util.EventListener
see
#getActionListeners
since
1.3

	EventListener l = null; 
	if  (listenerType == ActionListener.class) { 
	    l = actionListener;
	}
	return AWTEventMulticaster.getListeners(l, listenerType);
    
public java.awt.MenuShortcutgetShortcut()
Get the MenuShortcut object associated with this menu item,

return
the menu shortcut associated with this menu item, or null if none has been specified.
see
java.awt.MenuItem#setShortcut
since
JDK1.1

        return shortcut;
    
java.awt.MenuItemgetShortcutMenuItem(java.awt.MenuShortcut s)

        return (s.equals(shortcut)) ? this : null;
    
booleanhandleShortcut(java.awt.event.KeyEvent e)

        MenuShortcut s = new MenuShortcut(e.getKeyCode(),
                             (e.getModifiers() & InputEvent.SHIFT_MASK) > 0);
        // Fix For 6185151: Menu shortcuts of all menuitems within a menu 
        // should be disabled when the menu itself is disabled
        if (s.equals(shortcut) && isItemEnabled()) {
            // MenuShortcut match -- issue an event on keydown.
            if (e.getID() == KeyEvent.KEY_PRESSED) {
                doMenuEvent(e.getWhen(), e.getModifiers());
            } else {
                // silently eat key release.
            }
            return true;
        }
        return false;
    
private static native voidinitIDs()
Initialize JNI field and method IDs

public booleanisEnabled()
Checks whether this menu item is enabled.

see
java.awt.MenuItem#setEnabled
since
JDK1.0

	return enabled;
    
private final booleanisItemEnabled()

        // Fix For 6185151: Menu shortcuts of all menuitems within a menu 
        // should be disabled when the menu itself is disabled
        if (!isEnabled()) {
            return false;
        }
        MenuContainer container = getParent_NoClientCode();
        do {
            if (!(container instanceof Menu)) {
                return true;
            } 
            Menu menu = (Menu)container;
            if (!menu.isEnabled()) {
                return false;
            }
            container = menu.getParent_NoClientCode();
        } while (container != null);
        return true;
    
public java.lang.StringparamString()
Returns a string representing the state of this MenuItem. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

return
the parameter string of this menu item

        String str = ",label=" + label;
        if (shortcut != null) {
            str += ",shortcut=" + shortcut;
        }
        return super.paramString() + str;
    
protected voidprocessActionEvent(java.awt.event.ActionEvent e)
Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects. This method is not called unless action events are enabled for this component. Action events are enabled when one of the following occurs:

  • An ActionListener object is registered via addActionListener.
  • Action events are enabled via enableEvents.

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

param
e the action event
see
java.awt.event.ActionEvent
see
java.awt.event.ActionListener
see
java.awt.MenuItem#enableEvents
since
JDK1.1

        ActionListener listener = actionListener;
        if (listener != null) {
            listener.actionPerformed(e);
        }
    
protected voidprocessEvent(java.awt.AWTEvent e)
Processes events on this menu item. If the event is an instance of ActionEvent, it invokes processActionEvent, another method defined by MenuItem.

Currently, menu items only support action events.

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

param
e the event
see
java.awt.MenuItem#processActionEvent
since
JDK1.1

        if (e instanceof ActionEvent) {
            processActionEvent((ActionEvent)e);
        }
    
private voidreadObject(java.io.ObjectInputStream s)
Reads the ObjectInputStream and if it isn't null adds a listener to receive action events fired by the Menu Item. Unrecognized keys or values will be ignored.

param
s the ObjectInputStream to read
exception
HeadlessException if GraphicsEnvironment.isHeadless returns true
see
#removeActionListener(ActionListener)
see
#addActionListener(ActionListener)
see
#writeObject(ObjectOutputStream)

      // HeadlessException will be thrown from MenuComponent's readObject
      s.defaultReadObject();

      Object keyOrNull;
      while(null != (keyOrNull = s.readObject())) {
	String key = ((String)keyOrNull).intern();

	if (actionListenerK == key)
	  addActionListener((ActionListener)(s.readObject()));

	else // skip value for unrecognized key
	  s.readObject();
      }
    
public synchronized voidremoveActionListener(java.awt.event.ActionListener l)
Removes the specified action listener so it no longer receives action events from this menu item. If l is null, no exception is thrown and no action is performed.

Refer to AWT Threading Issues for details on AWT's threading model.

param
l the action listener.
see
#addActionListener
see
#getActionListeners
see
java.awt.event.ActionEvent
see
java.awt.event.ActionListener
since
JDK1.1

	if (l == null) {
	    return;
	}
	actionListener = AWTEventMulticaster.remove(actionListener, l);
    
public voidsetActionCommand(java.lang.String command)
Sets the command name of the action event that is fired by this menu item.

By default, the action command is set to the label of the menu item.

param
command the action command to be set for this menu item.
see
java.awt.MenuItem#getActionCommand
since
JDK1.1

        actionCommand = command;
    
public synchronized voidsetEnabled(boolean b)
Sets whether or not this menu item can be chosen.

param
b if true, enables this menu item; if false, disables it.
see
java.awt.MenuItem#isEnabled
since
JDK1.1

    	enable(b);
    
public synchronized voidsetLabel(java.lang.String label)
Sets the label for this menu item to the specified label.

param
label the new label, or null for no label.
see
java.awt.MenuItem#getLabel
since
JDK1.0

	this.label = label;
	MenuItemPeer peer = (MenuItemPeer)this.peer;
	if (peer != null) {
	    peer.setLabel(label);
	}
    
public voidsetShortcut(java.awt.MenuShortcut s)
Set the MenuShortcut object associated with this menu item. If a menu shortcut is already associated with this menu item, it is replaced.

param
s the menu shortcut to associate with this menu item.
see
java.awt.MenuItem#getShortcut
since
JDK1.1

        shortcut = s;
	MenuItemPeer peer = (MenuItemPeer)this.peer;
	if (peer != null) {
	    peer.setLabel(label);
	}
    
private voidwriteObject(java.io.ObjectOutputStream s)
Writes default serializable fields to stream. Writes a list of serializable ActionListeners as optional data. The non-serializable listeners are detected and no attempt is made to serialize them.

param
s the ObjectOutputStream to write
serialData
null terminated sequence of 0 or more pairs; the pair consists of a String and an Object; the String indicates the type of object and is one of the following: actionListenerK indicating an ActionListener object
see
AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
see
#readObject(ObjectInputStream)


                                                                                                    
       
       
    
      s.defaultWriteObject();

      AWTEventMulticaster.save(s, actionListenerK, actionListener);
      s.writeObject(null);