FileDocCategorySizeDatePackage
JPopupMenu.javaAPI DocJava SE 5 API49605Fri Aug 26 14:57:56 BST 2005javax.swing

JPopupMenu

public class JPopupMenu extends JComponent implements MenuElement, Accessible
An implementation of a popup menu -- a small window that pops up and displays a series of choices. A JPopupMenu is used for the menu that appears when the user selects an item on the menu bar. It is also used for "pull-right" menu that appears when the selects a menu item that activates it. Finally, a JPopupMenu can also be used anywhere else you want a menu to appear. For example, when the user right-clicks in a specified area.

For information and examples of using popup menus, see How to Use Menus in The Java Tutorial.

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: A small window that pops up and displays a series of choices.
version
1.191 @(#)JPopupMenu.java 1.191
author
Georges Saab
author
David Karlton
author
Arnaud Weber

Fields Summary
private static final String
uiClassID
private static final Object
defaultLWPopupEnabledKey
Key used in AppContext to determine if light way popups are the default.
static boolean
popupPostionFixDisabled
Bug#4425878-Property javax.swing.adjustPopupLocationToFit introduced
transient Component
invoker
transient Popup
popup
transient Frame
frame
private int
desiredLocationX
private int
desiredLocationY
private String
label
private boolean
paintBorder
private Insets
margin
private boolean
lightWeightPopup
Used to indicate if lightweight popups should be used.
private SingleSelectionModel
selectionModel
private static final Object
classLock
private static final boolean
TRACE
private static final boolean
VERBOSE
private static final boolean
DEBUG
Constructors Summary
public JPopupMenu()
Constructs a JPopupMenu without an "invoker".

        this(null);
    
public JPopupMenu(String label)
Constructs a JPopupMenu with the specified title.

param
label the string that a UI may use to display as a title for the popup menu.

        this.label = label;
        lightWeightPopup = getDefaultLightWeightPopupEnabled();
        setSelectionModel(new DefaultSingleSelectionModel());
        enableEvents(AWTEvent.MOUSE_EVENT_MASK);
	setFocusTraversalKeysEnabled(false);
        updateUI();
    
Methods Summary
public javax.swing.JMenuItemadd(javax.swing.JMenuItem menuItem)
Appends the specified menu item to the end of this menu.

param
menuItem the JMenuItem to add
return
the JMenuItem added

        super.add(menuItem);
        return menuItem;
    
public javax.swing.JMenuItemadd(java.lang.String s)
Creates a new menu item with the specified text and appends it to the end of this menu.

param
s the string for the menu item to be added

        return add(new JMenuItem(s));
    
public javax.swing.JMenuItemadd(javax.swing.Action a)
Appends a new menu item to the end of the menu which dispatches the specified Action object. As of JDK 1.3, this is no longer the preferred method for adding Actions to a container. Instead it is recommended to configure a control with an action using setAction, and then add that control directly to the Container.

param
a the Action to add to the menu
return
the new menu item
see
Action

	JMenuItem mi = createActionComponent(a);
	mi.setAction(a);
        add(mi);
        return mi;
    
public voidaddMenuKeyListener(javax.swing.event.MenuKeyListener l)
Adds a MenuKeyListener to the popup menu.

param
l the MenuKeyListener to be added
since
1.5

        listenerList.add(MenuKeyListener.class, l);
    
public voidaddPopupMenuListener(javax.swing.event.PopupMenuListener l)
Adds a PopupMenu listener.

param
l the PopupMenuListener to add

        listenerList.add(PopupMenuListener.class,l);
    
public voidaddSeparator()
Appends a new separator at the end of the menu.

        add( new JPopupMenu.Separator() );
    
java.awt.PointadjustPopupLocationToFitScreen(int xposition, int yposition)
Returns an point which has been adjusted to take into account of the desktop bounds, taskbar and multi-monitor configuration.

This adustment may be cancelled by invoking the application with -Djavax.swing.adjustPopupLocationToFit=false

	Point p = new Point(xposition, yposition);

        if(popupPostionFixDisabled == true || GraphicsEnvironment.isHeadless())
            return p;

        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Rectangle screenBounds;
        Insets screenInsets;
        GraphicsConfiguration gc = null;
        // Try to find GraphicsConfiguration, that includes mouse
        // pointer position
        GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gd = ge.getScreenDevices();
        for(int i = 0; i < gd.length; i++) {
            if(gd[i].getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
                GraphicsConfiguration dgc =
                    gd[i].getDefaultConfiguration();
                if(dgc.getBounds().contains(p)) {
                    gc = dgc;
                    break;
                }
            }
        }

        // If not found and we have invoker, ask invoker about his gc
        if(gc == null && getInvoker() != null) {
            gc = getInvoker().getGraphicsConfiguration();
        }

        if(gc != null) {
            // If we have GraphicsConfiguration use it to get
            // screen bounds and insets
            screenInsets = toolkit.getScreenInsets(gc);
            screenBounds = gc.getBounds();
        } else {
            // If we don't have GraphicsConfiguration use primary screen
            // and empty insets
            screenInsets = new Insets(0, 0, 0, 0);
            screenBounds = new Rectangle(toolkit.getScreenSize());
        }

        int scrWidth = screenBounds.width -
                    Math.abs(screenInsets.left+screenInsets.right);
        int scrHeight = screenBounds.height -
                    Math.abs(screenInsets.top+screenInsets.bottom);

        Dimension size;

        size = JPopupMenu.this.getPreferredSize();

        if( (p.x + size.width) > screenBounds.x + scrWidth )
             p.x = screenBounds.x + scrWidth - size.width;

        if( (p.y + size.height) > screenBounds.y + scrHeight)
             p.y = screenBounds.y + scrHeight - size.height;

        /* Change is made to the desired (X,Y) values, when the
           PopupMenu is too tall OR too wide for the screen
        */
        if( p.x < screenBounds.x )
            p.x = screenBounds.x ;
        if( p.y < screenBounds.y )
            p.y = screenBounds.y;

        return p;
    
booleanalwaysOnTop()
Always returns true since popups, by definition, should always be on top of all other windows.

return
true

	return true;
    
protected java.beans.PropertyChangeListenercreateActionChangeListener(javax.swing.JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur. As of JDK 1.3, this is no longer the preferred method for adding Actions to a container. Instead it is recommended to configure a control with an action using setAction, and then add that control directly to the Container.

        return new ActionChangedListener(b);
    
protected javax.swing.JMenuItemcreateActionComponent(javax.swing.Action a)
Factory method which creates the JMenuItem for Actions added to the JPopupMenu. As of JDK 1.3, this is no longer the preferred method, instead it is recommended to configure a control with an action using setAction, and then adding that control directly to the Container.

param
a the Action for the menu item to be added
return
the new menu item
see
Action
since
1.3

        JMenuItem mi = new JMenuItem((String)a.getValue(Action.NAME),
                                     (Icon)a.getValue(Action.SMALL_ICON)){
	    protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
		PropertyChangeListener pcl = createActionChangeListener(this);
		if (pcl == null) {
		    pcl = super.createActionPropertyChangeListener(a);
		}
		return pcl;
	    }
	};
        mi.setHorizontalTextPosition(JButton.TRAILING);
        mi.setVerticalTextPosition(JButton.CENTER);
        mi.setEnabled(a.isEnabled());
	return mi;
    
private 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

        Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuKeyListener.class) {
                ((MenuKeyListener)listeners[i+1]).menuKeyPressed(event);
            }
        }
    
private 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

        Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuKeyListener.class) {
                ((MenuKeyListener)listeners[i+1]).menuKeyReleased(event);
            }
        }
    
private 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

        Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==MenuKeyListener.class) {
                ((MenuKeyListener)listeners[i+1]).menuKeyTyped(event);
            }
        }
    
protected voidfirePopupMenuCanceled()
Notifies PopupMenuListeners that this popup menu is cancelled.

        Object[] listeners = listenerList.getListenerList();
        PopupMenuEvent e=null;
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==PopupMenuListener.class) {
                if (e == null)
                    e = new PopupMenuEvent(this);
                ((PopupMenuListener)listeners[i+1]).popupMenuCanceled(e);
            }
        }    
    
protected voidfirePopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that this popup menu will become invisible.

        Object[] listeners = listenerList.getListenerList();
        PopupMenuEvent e=null;
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==PopupMenuListener.class) {
                if (e == null)
                    e = new PopupMenuEvent(this);
                ((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeInvisible(e);
            }
        }            
    
protected voidfirePopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that this popup menu will become visible.

        Object[] listeners = listenerList.getListenerList();
        PopupMenuEvent e=null;
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==PopupMenuListener.class) {
                if (e == null)
                    e = new PopupMenuEvent(this);
                ((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeVisible(e);
            }
        }    
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this JPopupMenu. For JPopupMenus, the AccessibleContext takes the form of an AccessibleJPopupMenu. A new AccessibleJPopupMenu instance is created if necessary.

return
an AccessibleJPopupMenu that serves as the AccessibleContext of this JPopupMenu

        if (accessibleContext == null) {
            accessibleContext = new AccessibleJPopupMenu();
        }
        return accessibleContext;
    
public java.awt.ComponentgetComponent()
Returns this JPopupMenu component.

return
this JPopupMenu object
see
MenuElement#getComponent

        return this;
    
public java.awt.ComponentgetComponentAtIndex(int i)
Returns the component at the specified index.

param
i the index of the component, where 0 is the first
return
the Component at that index
deprecated
replaced by getComponent(int i)

        return getComponent(i);
    
public intgetComponentIndex(java.awt.Component c)
Returns the index of the specified component.

param
c the Component to find
return
the index of the component, where 0 is the first; or -1 if the component is not found

        int ncomponents = this.getComponentCount();
        Component[] component = this.getComponents();
        for (int i = 0 ; i < ncomponents ; i++) {
            Component comp = component[i];
            if (comp == c) 
                return i;
        }
        return -1;
    
public static booleangetDefaultLightWeightPopupEnabled()
Gets the defaultLightWeightPopupEnabled property, which by default is true.

return
the value of the defaultLightWeightPopupEnabled property
see
#setDefaultLightWeightPopupEnabled

        Boolean b = (Boolean)
            SwingUtilities.appContextGet(defaultLWPopupEnabledKey);
        if (b == null) {
            SwingUtilities.appContextPut(defaultLWPopupEnabledKey, 
                                         Boolean.TRUE);
            return true;
        }
        return b.booleanValue();
    
private static java.awt.FramegetFrame(java.awt.Component c)

        Component w = c;

        while(!(w instanceof Frame) && (w!=null)) {
            w = w.getParent();
        }
        return (Frame)w;
    
public java.awt.ComponentgetInvoker()
Returns the component which is the 'invoker' of this popup menu.

return
the Component in which the popup menu is displayed

        return this.invoker;
    
public java.lang.StringgetLabel()
Returns the popup menu's label

return
a string containing the popup menu's label
see
#setLabel

        return label;
    
public java.awt.InsetsgetMargin()
Returns the margin, in pixels, between the popup menu's border and its containees.

return
an Insets object containing the margin values.

        if(margin == null) {
            return new Insets(0,0,0,0);
        } else {
            return margin;
        }
    
public javax.swing.event.MenuKeyListener[]getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JPopupMenu with addMenuKeyListener().

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

        return (MenuKeyListener[])listenerList.getListeners(
                MenuKeyListener.class);
    
private javax.swing.PopupgetPopup()
Returns a Popup instance from the PopupMenuUI that has had show invoked on it. If the current popup is non-null, this will invoke dispose of it, and then show the new one.

This does NOT fire any events, it is up the caller to dispatch the necessary events.

        Popup oldPopup = popup;

        if (oldPopup != null) {
            oldPopup.hide();
        }
        PopupFactory popupFactory = PopupFactory.getSharedInstance();

        if (isLightWeightPopupEnabled()) {
            popupFactory.setPopupType(PopupFactory.LIGHT_WEIGHT_POPUP);
        }
        else {
            popupFactory.setPopupType(PopupFactory.MEDIUM_WEIGHT_POPUP);
        }

        // adjust the location of the popup
        Point p = adjustPopupLocationToFitScreen(desiredLocationX,desiredLocationY);
	desiredLocationX = p.x;
	desiredLocationY = p.y;

        Popup newPopup = getUI().getPopup(this, desiredLocationX,
                                          desiredLocationY);

        popupFactory.setPopupType(PopupFactory.LIGHT_WEIGHT_POPUP);
        newPopup.show();
        return newPopup;
    
public javax.swing.event.PopupMenuListener[]getPopupMenuListeners()
Returns an array of all the PopupMenuListeners added to this JMenuItem with addPopupMenuListener().

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

        return (PopupMenuListener[])listenerList.getListeners(
                PopupMenuListener.class);
    
javax.swing.JPopupMenugetRootPopupMenu()
Returns the popup menu which is at the root of the menu system for this popup menu.

return
the topmost grandparent JPopupMenu

        JPopupMenu mp = this;
        while((mp!=null) && (mp.isPopupMenu()!=true) &&
              (mp.getInvoker() != null) &&
              (mp.getInvoker().getParent() != null) &&
              (mp.getInvoker().getParent() instanceof JPopupMenu)
              ) {
            mp = (JPopupMenu) mp.getInvoker().getParent();
        }
        return mp;
    
public javax.swing.SingleSelectionModelgetSelectionModel()
Returns the model object that handles single selections.

return
the selectionModel property
see
SingleSelectionModel

        return selectionModel;
    
public javax.swing.MenuElement[]getSubElements()
Returns an array of MenuElements containing the submenu for this menu component. It will only return items conforming to the JMenuElement interface. If popup menu is null returns an empty array. This method is required to conform to the MenuElement interface.

return
an array of MenuElement objects
see
MenuElement#getSubElements

        MenuElement result[];
        Vector tmp = new Vector();
        int c = getComponentCount();
        int i;
        Component m;

        for(i=0 ; i < c ; i++) {
            m = getComponent(i);
            if(m instanceof MenuElement)
                tmp.addElement(m);
        }

        result = new MenuElement[tmp.size()];
        for(i=0,c=tmp.size() ; i < c ; i++) 
            result[i] = (MenuElement) tmp.elementAt(i);
        return result;
    
public javax.swing.plaf.PopupMenuUIgetUI()
Returns the look and feel (L&F) object that renders this component.

return
the PopupMenuUI object that renders this component

        return (PopupMenuUI)ui;
    
public java.lang.StringgetUIClassID()
Returns the name of the L&F class that renders this component.

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

        return uiClassID;
    
public voidinsert(javax.swing.Action a, int index)
Inserts a menu item for the specified Action object at a given position.

param
a the Action object to insert
param
index specifies the position at which to insert the Action, where 0 is the first
exception
IllegalArgumentException if index < 0
see
Action

	JMenuItem mi = createActionComponent(a);
	mi.setAction(a);
        insert(mi, index);
    
public voidinsert(java.awt.Component component, int index)
Inserts the specified component into the menu at a given position.

param
component the Component to insert
param
index specifies the position at which to insert the component, where 0 is the first
exception
IllegalArgumentException if index < 0

        if (index < 0) {
            throw new IllegalArgumentException("index less than zero.");
        }

        int nitems = getComponentCount();
	// PENDING(ges): Why not use an array?
        Vector tempItems = new Vector();

        /* Remove the item at index, nitems-index times 
           storing them in a temporary vector in the
           order they appear on the menu.
           */
        for (int i = index ; i < nitems; i++) {
            tempItems.addElement(getComponent(index));
            remove(index);
        }

        add(component);

        /* Add the removed items back to the menu, they are
           already in the correct order in the temp vector.
           */
        for (int i = 0; i < tempItems.size()  ; i++) {
            add((Component)tempItems.elementAt(i));
        }
    
public booleanisBorderPainted()
Checks whether the border should be painted.

return
true if the border is painted, false otherwise
see
#setBorderPainted

        return paintBorder;
    
public booleanisLightWeightPopupEnabled()
Gets the lightWeightPopupEnabled property.

return
the value of the lightWeightPopupEnabled property
see
#setLightWeightPopupEnabled

        return lightWeightPopup;
    
private booleanisPopupMenu()
Returns true if the popup menu is a standalone popup menu rather than the submenu of a JMenu.

return
true if this menu is a standalone popup menu, otherwise false

        return  ((invoker != null) && !(invoker instanceof JMenu));
    
public booleanisPopupTrigger(java.awt.event.MouseEvent e)
Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu's currently installed UI.

return
true if the mouse event is a popup trigger
since
1.3

	return getUI().isPopupTrigger(e);
    
booleanisSubPopupMenu(javax.swing.JPopupMenu popup)
Examines the list of menu items to determine whether popup is a popup menu.

param
popup a JPopupMenu
return
true if popup

        int ncomponents = this.getComponentCount();
        Component[] component = this.getComponents();
        for (int i = 0 ; i < ncomponents ; i++) {
            Component comp = component[i];
            if (comp instanceof JMenu) {
                JMenu menu = (JMenu)comp;
                JPopupMenu subPopup = menu.getPopupMenu();
                if (subPopup == popup)
                    return true;
                if (subPopup.isSubPopupMenu(popup))
                    return true;
            }
        }
        return false;
    
public booleanisVisible()
Returns true if the popup menu is visible (currently being displayed).

	if(popup != null)
	    return true;
	else
	    return false;
    
public voidmenuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this menu. This implements the javax.swing.MenuElement interface. Overrides MenuElement.menuSelectionChanged.

param
isIncluded true if this menu is active, false if it is not
see
MenuElement#menuSelectionChanged(boolean)

	if (DEBUG) {
	    System.out.println("In JPopupMenu.menuSelectionChanged " + isIncluded);
	}
        if(invoker instanceof JMenu) {
            JMenu m = (JMenu) invoker;
            if(isIncluded) 
                m.setPopupMenuVisible(true);
            else
                m.setPopupMenuVisible(false);
        }
        if (isPopupMenu() && !isIncluded)
          setVisible(false);
    
public voidpack()
Lays out the container so that it uses the minimum space needed to display its contents.

        if(popup != null) {
            Dimension pref = getPreferredSize();

            if (pref == null || pref.width != getWidth() ||
                                pref.height != getHeight()) {
                popup = getPopup();
            } else {
                validate();
            }
        }
    
protected voidpaintBorder(java.awt.Graphics g)
Paints the popup menu's border if the borderPainted property is true.

param
g the Graphics object
see
JComponent#paint
see
JComponent#setBorder

    
        if (isBorderPainted()) {
            super.paintBorder(g);
        }
    
protected java.lang.StringparamString()
Returns a string representation of this JPopupMenu. 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 JPopupMenu.

	String labelString = (label != null ?
			      label : "");
	String paintBorderString = (paintBorder ?
				    "true" : "false");
	String marginString = (margin != null ?
			      margin.toString() : "");
	String lightWeightPopupEnabledString = (isLightWeightPopupEnabled() ?
						"true" : "false");	
	return super.paramString() +
	    ",desiredLocationX=" + desiredLocationX +
	    ",desiredLocationY=" + desiredLocationY +
	",label=" + labelString +
	",lightWeightPopupEnabled=" + lightWeightPopupEnabledString +
	",margin=" + marginString +
	",paintBorder=" + paintBorderString;
    
protected voidprocessFocusEvent(java.awt.event.FocusEvent evt)

	super.processFocusEvent(evt);
    
protected voidprocessKeyEvent(java.awt.event.KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.

param
evt the key event to be processed

        MenuSelectionManager.defaultManager().processKeyEvent(evt);
	if (evt.isConsumed()) {
	    return;
	}
	super.processKeyEvent(evt);
    
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

        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();
    }
    
private voidprocessMenuKeyEvent(javax.swing.event.MenuKeyEvent e)
Handles a keystroke in a menu.

param
e a MenuKeyEvent object
since
1.5

        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 event, javax.swing.MenuElement[] path, javax.swing.MenuSelectionManager manager)
This method is required to conform to the MenuElement interface, but it not implemented.

see
MenuElement#processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)

private voidreadObject(java.io.ObjectInputStream s)

        s.defaultReadObject();

        Vector          values = (Vector)s.readObject();
        int             indexCounter = 0;
        int             maxCounter = values.size();

        if(indexCounter < maxCounter && values.elementAt(indexCounter).
           equals("invoker")) {
            invoker = (Component)values.elementAt(++indexCounter);
            indexCounter++;
        }
        if(indexCounter < maxCounter && values.elementAt(indexCounter).
           equals("popup")) {
            popup = (Popup)values.elementAt(++indexCounter);
            indexCounter++;
        }
    
public voidremove(int pos)
Removes the component at the specified index from this popup menu.

param
pos the position of the item to be removed
exception
IllegalArgumentException if the value of pos < 0, or if the value of pos is greater than the number of items

        if (pos < 0) {
            throw new IllegalArgumentException("index less than zero.");
        }
        if (pos > getComponentCount() -1) {
            throw new IllegalArgumentException("index greater than the number of items.");
        }
	super.remove(pos);
    
public voidremoveMenuKeyListener(javax.swing.event.MenuKeyListener l)
Removes a MenuKeyListener from the popup menu.

param
l the MenuKeyListener to be removed
since
1.5

        listenerList.remove(MenuKeyListener.class, l);
    
public voidremovePopupMenuListener(javax.swing.event.PopupMenuListener l)
Removes a PopupMenu listener.

param
l the PopupMenuListener to remove

        listenerList.remove(PopupMenuListener.class,l);
    
public voidsetBorderPainted(boolean b)
Sets whether the border should be painted.

param
b if true, the border is painted.
see
#isBorderPainted
beaninfo
description: Is the border of the popup menu painted

        paintBorder = b;
        repaint();
    
public static voidsetDefaultLightWeightPopupEnabled(boolean aFlag)
Sets the default value of the lightWeightPopupEnabled property.

param
aFlag true if popups can be lightweight, otherwise false
see
#getDefaultLightWeightPopupEnabled
see
#setLightWeightPopupEnabled

  // show bad params, misc.

                                                  
         
        SwingUtilities.appContextPut(defaultLWPopupEnabledKey, 
                                     Boolean.valueOf(aFlag));
    
public voidsetInvoker(java.awt.Component invoker)
Sets the invoker of this popup menu -- the component in which the popup menu menu is to be displayed.

param
invoker the Component in which the popup menu is displayed
beaninfo
description: The invoking component for the popup menu expert: true

        Component oldInvoker = this.invoker;
        this.invoker = invoker;
        if ((oldInvoker != this.invoker) && (ui != null)) {
            ui.uninstallUI(this);
            ui.installUI(this);
        }               
        invalidate();
    
public voidsetLabel(java.lang.String label)
Sets the popup menu's label. Different look and feels may choose to display or not display this.

param
label a string specifying the label for the popup menu
see
#setLabel
beaninfo
description: The label for the popup menu. bound: true

        String oldValue = this.label;
        this.label = label;
        firePropertyChange("label", oldValue, label);
        if (accessibleContext != null) {
            accessibleContext.firePropertyChange(
                AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
                oldValue, label);
        }
        invalidate();
        repaint();
    
public voidsetLightWeightPopupEnabled(boolean aFlag)
Sets the value of the lightWeightPopupEnabled property, which by default is true. By default, when a look and feel displays a popup, it can choose to use a lightweight (all-Java) popup. Lightweight popup windows are more efficient than heavyweight (native peer) windows, but lightweight and heavyweight components do not mix well in a GUI. If your application mixes lightweight and heavyweight components, you should disable lightweight popups. Some look and feels might always use heavyweight popups, no matter what the value of this property.

param
aFlag false to disable lightweight popups
beaninfo
description: Determines whether lightweight popups are used when possible expert: true
see
#isLightWeightPopupEnabled

        // NOTE: this use to set the flag on a shared JPopupMenu, which meant
        // this effected ALL JPopupMenus.
        lightWeightPopup = aFlag;
    
public voidsetLocation(int x, int y)
Sets the location of the upper left corner of the popup menu using x, y coordinates.

param
x the x coordinate of the popup's new position in the screen's coordinate space
param
y the y coordinate of the popup's new position in the screen's coordinate space
beaninfo
description: The location of the popup menu.

        int oldX = desiredLocationX;
        int oldY = desiredLocationY;

        desiredLocationX = x;
        desiredLocationY = y;
        if(popup != null && (x != oldX || y != oldY)) {
            popup = getPopup();
        }
    
public voidsetPopupSize(java.awt.Dimension d)
Sets the size of the Popup window using a Dimension object. This is equivalent to setPreferredSize(d).

param
d the Dimension specifying the new size of this component.
beaninfo
description: The size of the popup menu

        Dimension oldSize = getPreferredSize();

        setPreferredSize(d);
        if (popup != null) {
            Dimension newSize = getPreferredSize();

            if (!oldSize.equals(newSize)) {
                popup = getPopup();
            }
        }
    
public voidsetPopupSize(int width, int height)
Sets the size of the Popup window to the specified width and height. This is equivalent to setPreferredSize(new Dimension(width, height)).

param
width the new width of the Popup in pixels
param
height the new height of the Popup in pixels
beaninfo
description: The size of the popup menu

        setPopupSize(new Dimension(width, height));
    
public voidsetSelected(java.awt.Component sel)
Sets the currently selected component, This will result in a change to the selection model.

param
sel the Component to select
beaninfo
description: The selected component on the popup menu expert: true hidden: true

    
        SingleSelectionModel model = getSelectionModel();
        int index = getComponentIndex(sel);
        model.setSelectedIndex(index);
    
public voidsetSelectionModel(javax.swing.SingleSelectionModel model)
Sets the model object to handle single selections.

param
model the new SingleSelectionModel
see
SingleSelectionModel
beaninfo
description: The selection model for the popup menu expert: true

        selectionModel = model;
    
public voidsetUI(javax.swing.plaf.PopupMenuUI ui)
Sets the L&F object that renders this component.

param
ui the new PopupMenuUI 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);
    
public voidsetVisible(boolean b)
Sets the visibility of the popup menu.

param
b true to make the popup visible, or false to hide it
beaninfo
bound: true description: Makes the popup visible

	if (DEBUG) {
	    System.out.println("JPopupMenu.setVisible " + b);
	}

        // Is it a no-op?
        if (b == isVisible())
            return;

        // if closing, first close all Submenus
        if (b == false) {

	    // 4234793: This is a workaround because JPopupMenu.firePopupMenuCanceled is
	    // a protected method and cannot be called from BasicPopupMenuUI directly
	    // The real solution could be to make 
	    // firePopupMenuCanceled public and call it directly.
	    Boolean doCanceled = (Boolean)getClientProperty("JPopupMenu.firePopupMenuCanceled");
	    if (doCanceled != null && doCanceled == Boolean.TRUE) {
		putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.FALSE);
		firePopupMenuCanceled();
	    }
            getSelectionModel().clearSelection();
	    
        } else {
            // This is a popup menu with MenuElement children,
            // set selection path before popping up!
            if (isPopupMenu()) {
		if (getSubElements().length > 0) {
		    MenuElement me[] = new MenuElement[2];
		    me[0]=(MenuElement)this;
		    me[1]=getSubElements()[0];
		    MenuSelectionManager.defaultManager().setSelectedPath(me);
		} else {
		    MenuElement me[] = new MenuElement[1];
		    me[0]=(MenuElement)this;
		    MenuSelectionManager.defaultManager().setSelectedPath(me);
		}
	    }
        }

        if(b) {
            firePopupMenuWillBecomeVisible();
            popup = getPopup();
	    firePropertyChange("visible", Boolean.FALSE, Boolean.TRUE);

	   
	} else if(popup != null) {
            firePopupMenuWillBecomeInvisible();
            popup.hide();
            popup = null;
	    firePropertyChange("visible", Boolean.TRUE, Boolean.FALSE);
            // 4694797: When popup menu is made invisible, selected path
            // should be cleared
            if (isPopupMenu()) {
                MenuSelectionManager.defaultManager().clearSelectedPath();
            }
        }
    
public voidshow(java.awt.Component invoker, int x, int y)
Displays the popup menu at the position x,y in the coordinate space of the component invoker.

param
invoker the component in whose space the popup menu is to appear
param
x the x coordinate in invoker's coordinate space at which the popup menu is to be displayed
param
y the y coordinate in invoker's coordinate space at which the popup menu is to be displayed

	if (DEBUG) {
	    System.out.println("in JPopupMenu.show " );
	}
        setInvoker(invoker);
        Frame newFrame = getFrame(invoker);
        if (newFrame != frame) {
            // Use the invoker's frame so that events 
            // are propagated properly
            if (newFrame!=null) {
                this.frame = newFrame;
                if(popup != null) {
                    setVisible(false);
                }
            }
        }
	Point invokerOrigin;
	if (invoker != null) {
	    invokerOrigin = invoker.getLocationOnScreen();
	    setLocation(invokerOrigin.x + x, 
			invokerOrigin.y + y);
	} else {
	    setLocation(x, y);
	}
        setVisible(true);       
    
public voidupdateUI()
Resets the UI property to a value from the current look and feel.

see
JComponent#updateUI

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

        Vector      values = new Vector();

        s.defaultWriteObject();
        // Save the invoker, if its Serializable.
        if(invoker != null && invoker instanceof Serializable) {
            values.addElement("invoker");
            values.addElement(invoker);
        }
        // Save the popup, if its Serializable.
        if(popup != null && popup instanceof Serializable) {
            values.addElement("popup");
            values.addElement(popup);
        }
        s.writeObject(values);

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