FileDocCategorySizeDatePackage
JMenuItem.javaAPI DocJava SE 6 API30930Tue Jun 10 00:26:38 BST 2008javax.swing

JMenuItem

public class JMenuItem extends AbstractButton implements MenuElement, Accessible
An implementation of an item in a menu. A menu item is essentially a button sitting in a list. When the user selects the "button", the action associated with the menu item is performed. A JMenuItem contained in a JPopupMenu performs exactly that function.

Menu items can be configured, and to some degree controlled, by Actions. Using an Action with a menu item has many benefits beyond directly configuring a menu item. Refer to Swing Components Supporting Action for more details, and you can find more information in How to Use Actions, a section in The Java Tutorial.

For further documentation and for examples, see How to Use Menus in The Java Tutorial.

Warning: Swing is not thread safe. For more information see Swing's Threading Policy.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see {@link java.beans.XMLEncoder}.

beaninfo
attribute: isContainer false description: An item which can be selected in a menu.
version
1.128 08/08/06
author
Georges Saab
author
David Karlton
see
JPopupMenu
see
JMenu
see
JCheckBoxMenuItem
see
JRadioButtonMenuItem

Fields Summary
private static final String
uiClassID
private static final boolean
TRACE
private static final boolean
VERBOSE
private static final boolean
DEBUG
private boolean
isMouseDragged
private KeyStroke
accelerator
Constructors Summary
public JMenuItem()
Creates a JMenuItem with no set text or icon.


                  
      
        this(null, (Icon)null);
    
public JMenuItem(Icon icon)
Creates a JMenuItem with the specified icon.

param
icon the icon of the JMenuItem

        this(null, icon);
    
public JMenuItem(String text)
Creates a JMenuItem with the specified text.

param
text the text of the JMenuItem

        this(text, (Icon)null);
    
public JMenuItem(Action a)
Creates a menu item whose properties are taken from the specified Action.

param
a the action of the JMenuItem
since
1.3

        this();
	setAction(a);
    
public JMenuItem(String text, Icon icon)
Creates a JMenuItem with the specified text and icon.

param
text the text of the JMenuItem
param
icon the icon of the JMenuItem

        setModel(new DefaultButtonModel());
        init(text, icon);
        initFocusability();
    
public JMenuItem(String text, int mnemonic)
Creates a JMenuItem with the specified text and keyboard mnemonic.

param
text the text of the JMenuItem
param
mnemonic the keyboard mnemonic for the JMenuItem

        setModel(new DefaultButtonModel());
        init(text, null);
        setMnemonic(mnemonic);
        initFocusability();
    
Methods Summary
protected voidactionPropertyChanged(javax.swing.Action action, java.lang.String propertyName)
{@inheritDoc}

since
1.6

        if (propertyName == Action.ACCELERATOR_KEY) {
            configureAcceleratorFromAction(action);
        }
        else {
            super.actionPropertyChanged(action, propertyName);
        }
    
public voidaddMenuDragMouseListener(javax.swing.event.MenuDragMouseListener l)
Adds a MenuDragMouseListener to the menu item.

param
l the MenuDragMouseListener to be added

        listenerList.add(MenuDragMouseListener.class, l);
    
public voidaddMenuKeyListener(javax.swing.event.MenuKeyListener l)
Adds a MenuKeyListener to the menu item.

param
l the MenuKeyListener to be added

        listenerList.add(MenuKeyListener.class, l);
    
booleanalwaysOnTop()
Returns true since Menus, by definition, should always be on top of all other windows. If the menu is in an internal frame false is returned due to the rollover effect for windows laf where the menu is not always on top.

        // Fix for bug #4482165
        if (SwingUtilities.getAncestorOfClass(JInternalFrame.class, this) !=
                null) {
            return false;
        }
	return true;
    
voidconfigureAcceleratorFromAction(javax.swing.Action a)

        KeyStroke ks = (a==null) ? null :
            (KeyStroke)a.getValue(Action.ACCELERATOR_KEY);
        setAccelerator(ks);
    
protected voidconfigurePropertiesFromAction(javax.swing.Action a)
{@inheritDoc}

since
1.3

        super.configurePropertiesFromAction(a);
        configureAcceleratorFromAction(a);
    
protected voidfireMenuDragMouseDragged(javax.swing.event.MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.

param
event a MenuDragMouseEvent
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuDragMouseListener.class) {
                // Lazily create the event:
                ((MenuDragMouseListener)listeners[i+1]).menuDragMouseDragged(event);
            }          
        }
    
protected voidfireMenuDragMouseEntered(javax.swing.event.MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.

param
event a MenuMouseDragEvent
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuDragMouseListener.class) {
                // Lazily create the event:
                ((MenuDragMouseListener)listeners[i+1]).menuDragMouseEntered(event);
            }          
        }
    
protected voidfireMenuDragMouseExited(javax.swing.event.MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.

param
event a MenuDragMouseEvent
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuDragMouseListener.class) {
                // Lazily create the event:
                ((MenuDragMouseListener)listeners[i+1]).menuDragMouseExited(event);
            }          
        }
    
protected voidfireMenuDragMouseReleased(javax.swing.event.MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.

param
event a MenuDragMouseEvent
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuDragMouseListener.class) {
                // Lazily create the event:
                ((MenuDragMouseListener)listeners[i+1]).menuDragMouseReleased(event);
            }          
        }
    
protected voidfireMenuKeyPressed(javax.swing.event.MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.

param
event a MenuKeyEvent
see
EventListenerList

	if (DEBUG) {
	    System.out.println("in JMenuItem.fireMenuKeyPressed for " + getText()+ 
				   "  " + KeyStroke.getKeyStrokeForEvent(event));
	}
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuKeyListener.class) {
                // Lazily create the event:
                ((MenuKeyListener)listeners[i+1]).menuKeyPressed(event);
            }          
        }
    
protected voidfireMenuKeyReleased(javax.swing.event.MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.

param
event a MenuKeyEvent
see
EventListenerList

	if (DEBUG) {
	    System.out.println("in JMenuItem.fireMenuKeyReleased for " + getText()+ 
				   "  " + KeyStroke.getKeyStrokeForEvent(event));
	}
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuKeyListener.class) {
                // Lazily create the event:
                ((MenuKeyListener)listeners[i+1]).menuKeyReleased(event);
            }          
        }
    
protected voidfireMenuKeyTyped(javax.swing.event.MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.

param
event a MenuKeyEvent
see
EventListenerList

	if (DEBUG) {
	    System.out.println("in JMenuItem.fireMenuKeyTyped for " + getText()+ 
				   "  " + KeyStroke.getKeyStrokeForEvent(event));
	}
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuKeyListener.class) {
                // Lazily create the event:
                ((MenuKeyListener)listeners[i+1]).menuKeyTyped(event);
            }          
        }
    
public javax.swing.KeyStrokegetAccelerator()
Returns the KeyStroke which serves as an accelerator for the menu item.

return
a KeyStroke object identifying the accelerator key

        return this.accelerator;
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Returns the AccessibleContext associated with this JMenuItem. For JMenuItems, the AccessibleContext takes the form of an AccessibleJMenuItem. A new AccessibleJMenuItme instance is created if necessary.

return
an AccessibleJMenuItem that serves as the AccessibleContext of this JMenuItem

        if (accessibleContext == null) {
            accessibleContext = new AccessibleJMenuItem();
        }
        return accessibleContext;
    
public java.awt.ComponentgetComponent()
Returns the java.awt.Component used to paint this object. The returned component will be used to convert events and detect if an event is inside a menu component.

return
the Component that paints this menu item

        return this;
    
public javax.swing.event.MenuDragMouseListener[]getMenuDragMouseListeners()
Returns an array of all the MenuDragMouseListeners added to this JMenuItem with addMenuDragMouseListener().

return
all of the MenuDragMouseListeners added or an empty array if no listeners have been added
since
1.4

        return (MenuDragMouseListener[])listenerList.getListeners(
                MenuDragMouseListener.class);
    
public javax.swing.event.MenuKeyListener[]getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JMenuItem with addMenuKeyListener().

return
all of the MenuKeyListeners added or an empty array if no listeners have been added
since
1.4

        return (MenuKeyListener[])listenerList.getListeners(
                MenuKeyListener.class);
    
public javax.swing.MenuElement[]getSubElements()
This method returns an array containing the sub-menu components for this menu component.

return
an array of MenuElements

        return new MenuElement[0];
    
public java.lang.StringgetUIClassID()
Returns the suffix used to construct the name of the L&F class used to render this component.

return
the string "MenuItemUI"
see
JComponent#getUIClassID
see
UIDefaults#getUI

        return uiClassID;
    
protected voidinit(java.lang.String text, javax.swing.Icon icon)
Initializes the menu item with the specified text and icon.

param
text the text of the JMenuItem
param
icon the icon of the JMenuItem

        if(text != null) {
            setText(text);
        }
        
        if(icon != null) {
            setIcon(icon);
        }
        
        // Listen for Focus events
        addFocusListener(new MenuItemFocusListener());
        setUIProperty("borderPainted", Boolean.FALSE);
        setFocusPainted(false);
        setHorizontalTextPosition(JButton.TRAILING);
        setHorizontalAlignment(JButton.LEADING);
	updateUI();
    
voidinitFocusability()
Inititalizes the focusability of the the JMenuItem. JMenuItem's are focusable, but subclasses may want to be, this provides them the opportunity to override this and invoke something else, or nothing at all. Refer to {@link javax.swing.JMenu#initFocusability} for the motivation of this.

	setFocusable(false);
    
public booleanisArmed()
Returns whether the menu item is "armed".

return
true if the menu item is armed, and it can be selected
see
#setArmed

        ButtonModel model = (ButtonModel) getModel();
        return model.isArmed();
    
voidlargeIconChanged(javax.swing.Action a)

    
public voidmenuSelectionChanged(boolean isIncluded)
Called by the MenuSelectionManager when the MenuElement is selected or unselected.

param
isIncluded true if this menu item is on the part of the menu path that changed, false if this menu is part of the a menu path that changed, but this particular part of that path is still the same
see
MenuSelectionManager#setSelectedPath(MenuElement[])

        setArmed(isIncluded);
    
protected java.lang.StringparamString()
Returns a string representation of this JMenuItem. 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
a string representation of this JMenuItem

	return super.paramString();
    
public voidprocessKeyEvent(java.awt.event.KeyEvent e, javax.swing.MenuElement[] path, javax.swing.MenuSelectionManager manager)
Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager's API.

Note: you do not have to forward the event to sub-components. This is done automatically by the MenuSelectionManager.

param
e a KeyEvent
param
path the MenuElement path array
param
manager the MenuSelectionManager

	if (DEBUG) {
	    System.out.println("in JMenuItem.processKeyEvent/3 for " + getText() + 
				   "  " + KeyStroke.getKeyStrokeForEvent(e));
	}
        MenuKeyEvent mke = new MenuKeyEvent(e.getComponent(), e.getID(),
					     e.getWhen(), e.getModifiers(),
					     e.getKeyCode(), e.getKeyChar(),
					     path, manager);
        processMenuKeyEvent(mke);	
    
        if (mke.isConsumed())  {
            e.consume();
        }
    
public voidprocessMenuDragMouseEvent(javax.swing.event.MenuDragMouseEvent e)
Handles mouse drag in a menu.

param
e a MenuDragMouseEvent object

	switch (e.getID()) {
	case MouseEvent.MOUSE_ENTERED:
	    isMouseDragged = false; fireMenuDragMouseEntered(e); break;
	case MouseEvent.MOUSE_EXITED:
	    isMouseDragged = false; fireMenuDragMouseExited(e); break;
	case MouseEvent.MOUSE_DRAGGED:
	    isMouseDragged = true; fireMenuDragMouseDragged(e); break;
	case MouseEvent.MOUSE_RELEASED:
	    if(isMouseDragged) fireMenuDragMouseReleased(e); break;
	default: 
	    break;
	}
    
public voidprocessMenuKeyEvent(javax.swing.event.MenuKeyEvent e)
Handles a keystroke in a menu.

param
e a MenuKeyEvent object

	if (DEBUG) {
	    System.out.println("in JMenuItem.processMenuKeyEvent for " + getText()+ 
				   "  " + KeyStroke.getKeyStrokeForEvent(e));
	}
	switch (e.getID()) {
	case KeyEvent.KEY_PRESSED:
	    fireMenuKeyPressed(e); break;
	case KeyEvent.KEY_RELEASED:
	    fireMenuKeyReleased(e); break;
	case KeyEvent.KEY_TYPED:
	    fireMenuKeyTyped(e); break;
	default: 
	    break;
	}
    
public voidprocessMouseEvent(java.awt.event.MouseEvent e, javax.swing.MenuElement[] path, javax.swing.MenuSelectionManager manager)
Processes a mouse event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using the MenuSelectionManager's API.

Note: you do not have to forward the event to sub-components. This is done automatically by the MenuSelectionManager.

param
e a MouseEvent
param
path the MenuElement path array
param
manager the MenuSelectionManager

	processMenuDragMouseEvent(
		 new MenuDragMouseEvent(e.getComponent(), e.getID(),
					e.getWhen(),
					e.getModifiers(), e.getX(), e.getY(),
                                        e.getXOnScreen(), e.getYOnScreen(),
					e.getClickCount(), e.isPopupTrigger(),
					path, manager));
    
private voidreadObject(java.io.ObjectInputStream s)
See JComponent.readObject() for information about serialization in Swing.

        s.defaultReadObject();
	if (getUIClassID().equals(uiClassID)) {
	    updateUI();
	}
    
public voidremoveMenuDragMouseListener(javax.swing.event.MenuDragMouseListener l)
Removes a MenuDragMouseListener from the menu item.

param
l the MenuDragMouseListener to be removed

        listenerList.remove(MenuDragMouseListener.class, l);
    
public voidremoveMenuKeyListener(javax.swing.event.MenuKeyListener l)
Removes a MenuKeyListener from the menu item.

param
l the MenuKeyListener to be removed

        listenerList.remove(MenuKeyListener.class, l);
    
public voidsetAccelerator(javax.swing.KeyStroke keyStroke)
Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy. It is the UI's responsibility to install the correct action. Note that when the keyboard accelerator is typed, it will work whether or not the menu is currently displayed.

param
keyStroke the KeyStroke which will serve as an accelerator
beaninfo
description: The keystroke combination which will invoke the JMenuItem's actionlisteners without navigating the menu hierarchy bound: true preferred: true

	KeyStroke oldAccelerator = accelerator;
        this.accelerator = keyStroke;
        repaint();
        revalidate();
	firePropertyChange("accelerator", oldAccelerator, accelerator);
    
public voidsetArmed(boolean b)
Identifies the menu item as "armed". If the mouse button is released while it is over this item, the menu's action event will fire. If the mouse button is released elsewhere, the event will not fire and the menu item will be disarmed.

param
b true to arm the menu item so it can be selected
beaninfo
description: Mouse release will fire an action event hidden: true

        ButtonModel model = (ButtonModel) getModel();

        boolean oldValue = model.isArmed();
        if(model.isArmed() != b) {
            model.setArmed(b);
        }
    
public voidsetEnabled(boolean b)
Enables or disables the menu item.

param
b true to enable the item
beaninfo
description: Does the component react to user interaction bound: true preferred: true

        // Make sure we aren't armed!
        if (!b && !UIManager.getBoolean("MenuItem.disabledAreNavigable")) {
            setArmed(false);
        }
        super.setEnabled(b);
    
voidsetIconFromAction(javax.swing.Action a)

        Icon icon = null;
        if (a != null) {
            icon = (Icon)a.getValue(Action.SMALL_ICON);
        }
        setIcon(icon);
    
public voidsetModel(javax.swing.ButtonModel newModel)
{@inheritDoc}

        super.setModel(newModel);
        if(newModel instanceof DefaultButtonModel) {
            ((DefaultButtonModel)newModel).setMenuItem(true);
        }
    
public voidsetUI(javax.swing.plaf.MenuItemUI ui)
Sets the look and feel object that renders this component.

param
ui the JMenuItemUI L&F object
see
UIDefaults#getUI
beaninfo
bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.

        super.setUI(ui);
    
voidsmallIconChanged(javax.swing.Action a)

        setIconFromAction(a);
    
public voidupdateUI()
Resets the UI property with a value from the current look and feel.

see
JComponent#updateUI

        setUI((MenuItemUI)UIManager.getUI(this));
    
private voidwriteObject(java.io.ObjectOutputStream s)

        s.defaultWriteObject();
        if (getUIClassID().equals(uiClassID)) {
            byte count = JComponent.getWriteObjCounter(this);
            JComponent.setWriteObjCounter(this, --count);
            if (count == 0 && ui != null) {
                ui.installUI(this);
            }
        }