JavaTM 2 Platform
Std. Ed. v1.3.1

javax.swing
Class JPopupMenu

java.lang.Object
  |
  +--java.awt.Component
        |
        +--java.awt.Container
              |
              +--javax.swing.JComponent
                    |
                    +--javax.swing.JPopupMenu
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, MenuElement, Serializable
Direct Known Subclasses:
BasicComboPopup

public class JPopupMenu
extends JComponent
implements Accessible, MenuElement

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. For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions, see the JPopupMenu key assignments.

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. A future release of Swing will provide support for long term persistence.

See Also:
Serialized Form

Inner Class Summary
protected  class JPopupMenu.AccessibleJPopupMenu
          This class implements accessibility support for the JPopupMenu class.
static class JPopupMenu.Separator
          A popup menu-specific separator.
 
Inner classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Inner classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Inner classes inherited from class java.awt.Component
Component.AccessibleAWTComponent
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
JPopupMenu()
          Constructs a JPopupMenu without an "invoker".
JPopupMenu(String label)
          Constructs a JPopupMenu with the specified title.
 
Method Summary
 JMenuItem add(Action a)
          Appends a new menu item to the end of the menu which dispatches the specified Action object.
 JMenuItem add(JMenuItem menuItem)
          Appends the specified menu item to the end of this menu.
 JMenuItem add(String s)
          Creates a new menu item with the specified text and appends it to the end of this menu.
 void addPopupMenuListener(PopupMenuListener l)
          Adds a PopupMenu listener.
 void addSeparator()
          Appends a new separator at the end of the menu.
protected  PropertyChangeListener createActionChangeListener(JMenuItem b)
          Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
protected  JMenuItem createActionComponent(Action a)
          Factory method which creates the JMenuItem for Actions added to the JPopupMenu.
protected  void firePopupMenuCanceled()
          Notifies PopupMenuListeners that this popup menu is cancelled.
protected  void firePopupMenuWillBecomeInvisible()
          Notifies PopupMenuListeners that this popup menu will become invisible.
protected  void firePopupMenuWillBecomeVisible()
          Notifies PopupMenuListeners that this popup menu will become visible.
 AccessibleContext getAccessibleContext()
          Gets the AccessibleContext associated with this JPopupMenu.
 Component getComponent()
          Returns this JPopupMenu component.
 Component getComponentAtIndex(int i)
          Deprecated. replaced by getComponent(int i)
 int getComponentIndex(Component c)
          Returns the index of the specified component.
static boolean getDefaultLightWeightPopupEnabled()
          Returns true if this is a light weight popup component, false otherwise.
 Component getInvoker()
          Returns the component which is the 'invoker' of this popup menu.
 String getLabel()
          Returns the popup menu's label
 Insets getMargin()
          Returns the margin, in pixels, between the popup menu's border and its containees.
 SingleSelectionModel getSelectionModel()
          Returns the model object that handles single selections.
 MenuElement[] getSubElements()
          Returns an array of MenuElements containing the submenu for this menu component.
 PopupMenuUI getUI()
          Returns the look and feel (L&F) object that renders this component.
 String getUIClassID()
          Returns the name of the L&F class that renders this component.
 void insert(Action a, int index)
          Inserts a menu item for the specified Action object at a given position.
 void insert(Component component, int index)
          Inserts the specified component into the menu at a given position.
 boolean isBorderPainted()
          Checks whether the border should be painted.
 boolean isLightWeightPopupEnabled()
          Returns true if light weight (all-Java) popups are in use, or false if heavy weight (native peer) popups are being used.
 boolean isPopupTrigger(MouseEvent e)
          Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu's currently installed UI.
 boolean isVisible()
          Returns true if the popup menu is visible (currently being displayed).
 void menuSelectionChanged(boolean isIncluded)
          Messaged when the menubar selection changes to activate or deactivate this menu.
 void pack()
          Lays out the container so that it uses the minimum space needed to display its contents.
protected  void paintBorder(Graphics g)
          Paints the popup menu's border if BorderPainted property is true.
protected  String paramString()
          Returns a string representation of this JPopupMenu.
 void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
          This method is required to conform to the MenuElement interface, but it not implemented.
 void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)
          This method is required to conform to the MenuElement interface, but it not implemented.
 void remove(int pos)
          Removes the component at the specified index from this popup menu.
 void removePopupMenuListener(PopupMenuListener l)
          Removes a PopupMenu listener.
 void setBorderPainted(boolean b)
          Sets whether the border should be painted.
static void setDefaultLightWeightPopupEnabled(boolean aFlag)
          Sets the default value for the lightWeightPopupEnabled property.
 void setInvoker(Component invoker)
          Sets the invoker of this popup menu -- the component in which the popup menu menu is to be displayed.
 void setLabel(String label)
          Sets the popup menu's label.
 void setLightWeightPopupEnabled(boolean aFlag)
          When displaying the popup, JPopupMenu chooses to use a light weight popup if it fits.
 void setLocation(int x, int y)
          Sets the location of the upper left corner of the popup menu using x, y coordinates.
 void setPopupSize(Dimension d)
          Sets the size of the Popup window using a Dimension object.
 void setPopupSize(int width, int height)
          Sets the size of the Popup window to the specified width and height.
 void setSelected(Component sel)
          Sets the currently selected component, This will result in a change to the selection model.
 void setSelectionModel(SingleSelectionModel model)
          Sets the model object to handle single selections.
 void setUI(PopupMenuUI ui)
          Sets the L&F object that renders this component.
 void setVisible(boolean b)
          Sets the visibility of the popup menu.
 void show(Component invoker, int x, int y)
          Displays the popup menu at the position x,y in the coordinate space of the component invoker.
 void updateUI()
          Notification from the UIFactory that the L&F has changed.
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getVerifyInputWhenFocusTarget, getVisibleRect, getWidth, getX, getY, grabFocus, hasFocus, hide, isDoubleBuffered, isFocusCycleRoot, isFocusTraversable, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processFocusEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setUI, setVerifyInputWhenFocusTarget, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getLayout, insets, invalidate, isAncestorOf, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, removeAll, removeContainerListener, setLayout, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentOrientation, getCursor, getDropTarget, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getInputContext, getInputMethodRequests, getLocale, getLocation, getLocationOnScreen, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, imageUpdate, inside, isDisplayable, isEnabled, isLightweight, isShowing, isValid, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setLocale, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JPopupMenu

public JPopupMenu()
Constructs a JPopupMenu without an "invoker".

JPopupMenu

public JPopupMenu(String label)
Constructs a JPopupMenu with the specified title.
Parameters:
label - the string that a UI may use to display as a title for the popup menu.
Method Detail

setDefaultLightWeightPopupEnabled

public static void setDefaultLightWeightPopupEnabled(boolean aFlag)
Sets the default value for the lightWeightPopupEnabled property. Lightweight popup windows are more efficient than heavy weight windows, but light weight and heavy weight components do not mix well in a GUI, and in that situation a heavy weight may be required.
Parameters:
aFlag - true if the popup is to be light weight, otherwise false
See Also:
getDefaultLightWeightPopupEnabled()

getDefaultLightWeightPopupEnabled

public static boolean getDefaultLightWeightPopupEnabled()
Returns true if this is a light weight popup component, false otherwise.
Returns:
the lightWeightPopupEnabled property
See Also:
setDefaultLightWeightPopupEnabled(boolean)

getUI

public PopupMenuUI getUI()
Returns the look and feel (L&F) object that renders this component.
Returns:
the PopupMenuUI object that renders this component

setUI

public void setUI(PopupMenuUI ui)
Sets the L&F object that renders this component.
Parameters:
ui - the new PopupMenuUI L&F object
See Also:
UIDefaults.getUI(javax.swing.JComponent)

updateUI

public void updateUI()
Notification from the UIFactory that the L&F has changed. Called to replace the UI with the latest version from the UIFactory.
Overrides:
updateUI in class JComponent
See Also:
JComponent.updateUI()

getUIClassID

public String getUIClassID()
Returns the name of the L&F class that renders this component.
Overrides:
getUIClassID in class JComponent
Returns:
the string "PopupMenuUI"
See Also:
JComponent.getUIClassID(), UIDefaults.getUI(javax.swing.JComponent)

getSelectionModel

public SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.
Returns:
the selectionModel property
See Also:
SingleSelectionModel

setSelectionModel

public void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.
Parameters:
model - the new SingleSelectionModel
See Also:
SingleSelectionModel

add

public JMenuItem add(JMenuItem menuItem)
Appends the specified menu item to the end of this menu.
Parameters:
c - the JMenuItem to add
Returns:
the JMenuItem added

add

public JMenuItem add(String s)
Creates a new menu item with the specified text and appends it to the end of this menu.
Parameters:
s - the string for the menu item to be added

add

public JMenuItem add(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.
Parameters:
a - the Action to add to the menu
Returns:
the new menu item
See Also:
Action

createActionComponent

protected JMenuItem createActionComponent(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.
Parameters:
a - the Action for the menu item to be added
Returns:
the new menu item
See Also:
Action

createActionChangeListener

protected PropertyChangeListener createActionChangeListener(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.

remove

public void remove(int pos)
Removes the component at the specified index from this popup menu.
Overrides:
remove in class Container
Parameters:
pos - the position of the item to be removed
Throws:
IllegalArgumentException - if the value of pos < 0, or if the value of pos is greater than the number of items

setLightWeightPopupEnabled

public void setLightWeightPopupEnabled(boolean aFlag)
When displaying the popup, JPopupMenu chooses to use a light weight popup if it fits. This method allows you to disable this feature. You have to do disable it if your application mixes light weight and heavy weights components.
Parameters:
aFlag - true if the popup is to be light weight, otherwise false

isLightWeightPopupEnabled

public boolean isLightWeightPopupEnabled()
Returns true if light weight (all-Java) popups are in use, or false if heavy weight (native peer) popups are being used.
Returns:
true if light weight popups are in use, false otherwise

getLabel

public String getLabel()
Returns the popup menu's label
Returns:
a string containing the popup menu's label
See Also:
setLabel(java.lang.String)

setLabel

public void setLabel(String label)
Sets the popup menu's label. Different look and feels may choose to display or not display this.
Parameters:
label - a string specifying the label for the popup menu
See Also:
setLabel(java.lang.String)

addSeparator

public void addSeparator()
Appends a new separator at the end of the menu.

insert

public void insert(Action a,
                   int index)
Inserts a menu item for the specified Action object at a given position.
Parameters:
a - the Action object to insert
index - specifies the position at which to insert the Action, where 0 is the first
See Also:
Action

insert

public void insert(Component component,
                   int index)
Inserts the specified component into the menu at a given position.
Parameters:
component - the Component to insert
index - specifies the position at which to insert the component, where 0 is the first
Throws:
IllegalArgumentException - if index < 0

addPopupMenuListener

public void addPopupMenuListener(PopupMenuListener l)
Adds a PopupMenu listener.
Parameters:
l - the PopupMenuListener to add

removePopupMenuListener

public void removePopupMenuListener(PopupMenuListener l)
Removes a PopupMenu listener.
Parameters:
l - the PopupMenuListener to remove

firePopupMenuWillBecomeVisible

protected void firePopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that this popup menu will become visible.

firePopupMenuWillBecomeInvisible

protected void firePopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that this popup menu will become invisible.

firePopupMenuCanceled

protected void firePopupMenuCanceled()
Notifies PopupMenuListeners that this popup menu is cancelled.

pack

public void pack()
Lays out the container so that it uses the minimum space needed to display its contents.

setVisible

public void setVisible(boolean b)
Sets the visibility of the popup menu.
Overrides:
setVisible in class JComponent
Parameters:
b - true to make the popup visible, or false to hide it

isVisible

public boolean isVisible()
Returns true if the popup menu is visible (currently being displayed).
Overrides:
isVisible in class Component
Following copied from class: java.awt.Component
Returns:
true if the component is visible; false otherwise.
See Also:
Component.setVisible(boolean)

setLocation

public void setLocation(int x,
                        int y)
Sets the location of the upper left corner of the popup menu using x, y coordinates.
Overrides:
setLocation in class Component
Parameters:
x - the x coordinate of the popup's new position
y - the y coordinate of the popup's new position

getInvoker

public Component getInvoker()
Returns the component which is the 'invoker' of this popup menu.
Returns:
the Component in which the popup menu is displayed

setInvoker

public void setInvoker(Component invoker)
Sets the invoker of this popup menu -- the component in which the popup menu menu is to be displayed.
Parameters:
invoker - the Component in which the popup menu is displayed

show

public void show(Component invoker,
                 int x,
                 int y)
Displays the popup menu at the position x,y in the coordinate space of the component invoker.
Parameters:
invoker - the component in whose space the popup menu is to appear
x - the x coordinate in invoker's coordinate space at which the popup menu is to be displayed
y - the y coordinate in invoker's coordinate space at which the popup menu is to be displayed

getComponentAtIndex

public Component getComponentAtIndex(int i)
Deprecated. replaced by getComponent(int i)

Returns the component at the specified index.
Parameters:
i - the index of the component, where 0 is the first
Returns:
the Component at that index

getComponentIndex

public int getComponentIndex(Component c)
Returns the index of the specified component.
Parameters:
the - Component to find
Returns:
the index of the component, where 0 is the first; or -1 if the component is not found

setPopupSize

public void setPopupSize(Dimension d)
Sets the size of the Popup window using a Dimension object.
Parameters:
d - the Dimension specifying the new size of this component.

setPopupSize

public void setPopupSize(int width,
                         int height)
Sets the size of the Popup window to the specified width and height.
Parameters:
width - the new width of the Popup in pixels
height - the new height of the Popup in pixels

setSelected

public void setSelected(Component sel)
Sets the currently selected component, This will result in a change to the selection model.
Parameters:
sel - the Component to select

isBorderPainted

public boolean isBorderPainted()
Checks whether the border should be painted.
Returns:
true if the border is painted, false otherwise
See Also:
setBorderPainted(boolean)

setBorderPainted

public void setBorderPainted(boolean b)
Sets whether the border should be painted.
Parameters:
b - if true, the border is painted.
See Also:
isBorderPainted()

paintBorder

protected void paintBorder(Graphics g)
Paints the popup menu's border if BorderPainted property is true.
Overrides:
paintBorder in class JComponent
Parameters:
g - the Graphics object
See Also:
JComponent.paint(java.awt.Graphics), JComponent.setBorder(javax.swing.border.Border)

getMargin

public Insets getMargin()
Returns the margin, in pixels, between the popup menu's border and its containees.
Returns:
an Insets object containing the margin values.

paramString

protected String paramString()
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.
Overrides:
paramString in class JComponent
Returns:
a string representation of this JPopupMenu.

getAccessibleContext

public AccessibleContext getAccessibleContext()
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.
Specified by:
getAccessibleContext in interface Accessible
Overrides:
getAccessibleContext in class JComponent
Returns:
an AccessibleJPopupMenu that serves as the AccessibleContext of this JPopupMenu

processMouseEvent

public void processMouseEvent(MouseEvent event,
                              MenuElement[] path,
                              MenuSelectionManager manager)
This method is required to conform to the MenuElement interface, but it not implemented.
Specified by:
processMouseEvent in interface MenuElement
See Also:
MenuElement.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)

processKeyEvent

public void processKeyEvent(KeyEvent e,
                            MenuElement[] path,
                            MenuSelectionManager manager)
This method is required to conform to the MenuElement interface, but it not implemented.
Specified by:
processKeyEvent in interface MenuElement
See Also:
MenuElement.processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager)

menuSelectionChanged

public void menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this menu. This implements the javax.swing.MenuElement interface. Overrides MenuElement.menuSelectionChanged.
Specified by:
menuSelectionChanged in interface MenuElement
Parameters:
isIncluded - true if this menu is active, false if it is not
See Also:
MenuElement.menuSelectionChanged(boolean)

getSubElements

public 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.
Specified by:
getSubElements in interface MenuElement
Returns:
an array of MenuElement objects
See Also:
MenuElement.getSubElements()

getComponent

public Component getComponent()
Returns this JPopupMenu component.
Specified by:
getComponent in interface MenuElement
Returns:
this JPopupMenu object
See Also:
MenuElement.getComponent()

isPopupTrigger

public boolean isPopupTrigger(MouseEvent e)
Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu's currently installed UI.
Returns:
true if the mouse event is a popup trigger
Since:
1.3

JavaTM 2 Platform
Std. Ed. v1.3.1

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.

Java, Java 2D, and JDBC are trademarks or registered trademarks of Oracle and/or its affiliates, in the US and other countries.
Copyright © 1995, 2010 Oracle and/or its affiliates. All rights reserved.