Class JPopupMenu
- All Implemented Interfaces:
- ImageObserver,- MenuContainer,- Serializable,- Accessible,- MenuElement
- Direct Known Subclasses:
- BasicComboPopup
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: 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 JavaBeans
 has been added to the java.beans package.
 Please see XMLEncoder.
- Since:
- 1.2
- 
Nested Class SummaryNested ClassesModifier and TypeClassDescriptionprotected classThis class implements accessibility support for theJPopupMenuclass.static classA popup menu-specific separator.Nested classes/interfaces declared in class javax.swing.JComponentJComponent.AccessibleJComponentNested classes/interfaces declared in class java.awt.ContainerContainer.AccessibleAWTContainerNested classes/interfaces declared in class java.awt.ComponentComponent.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
- 
Field SummaryFields declared in class javax.swing.JComponentlistenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields declared in class java.awt.ComponentaccessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields declared in interface java.awt.image.ImageObserverABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
- 
Constructor SummaryConstructorsConstructorDescriptionConstructs aJPopupMenuwithout an "invoker".JPopupMenu(String label) Constructs aJPopupMenuwith the specified title.
- 
Method SummaryModifier and TypeMethodDescriptionCreates a new menu item with the specified text and appends it to the end of this menu.Appends a new menu item to the end of the menu which dispatches the specifiedActionobject.Appends the specified menu item to the end of this menu.voidAdds aMenuKeyListenerto the popup menu.voidAdds aPopupMenulistener.voidAppends a new separator at the end of the menu.protected PropertyChangeListenerReturns a properly configuredPropertyChangeListenerwhich updates the control as changes to theActionoccur.protected JMenuItemFactory method which creates theJMenuItemforActionsadded to theJPopupMenu.protected voidNotifiesPopupMenuListenersthat this popup menu is cancelled.protected voidNotifiesPopupMenuListeners that this popup menu will become invisible.protected voidNotifiesPopupMenuListeners that this popup menu will become visible.Gets the AccessibleContext associated with this JPopupMenu.Returns thisJPopupMenucomponent.getComponentAtIndex(int i) Deprecated.intReturns the index of the specified component.static booleanGets thedefaultLightWeightPopupEnabledproperty, which by default istrue.Returns the component which is the 'invoker' of this popup menu.getLabel()Returns the popup menu's labelReturns the margin, in pixels, between the popup menu's border and its containers.Returns an array of all theMenuKeyListeners added to this JPopupMenu with addMenuKeyListener().Returns an array of all thePopupMenuListeners added to this JMenuItem with addPopupMenuListener().Returns the model object that handles single selections.Returns an array ofMenuElements containing the submenu for this menu component.getUI()Returns the look and feel (L&F) object that renders this component.Returns the name of the L&F class that renders this component.voidInserts the specified component into the menu at a given position.voidInserts a menu item for the specifiedActionobject at a given position.booleanChecks whether the border should be painted.booleanGets thelightWeightPopupEnabledproperty.booleanReturns true if theMouseEventis considered a popup trigger by theJPopupMenu's currently installed UI.booleanReturns true if the popup menu is visible (currently being displayed).voidmenuSelectionChanged(boolean isIncluded) Messaged when the menubar selection changes to activate or deactivate this menu.voidpack()Lays out the container so that it uses the minimum space needed to display its contents.protected voidPaints the popup menu's border if theborderPaintedproperty istrue.protected StringReturns a string representation of thisJPopupMenu.protected voidprocessKeyEvent(KeyEvent evt) Processes key stroke events such as mnemonics and accelerators.voidprocessKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager) Processes a key event forwarded from theMenuSelectionManagerand changes the menu selection, if necessary, by usingMenuSelectionManager's API.voidprocessMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) This method is required to conform to theMenuElementinterface, but it not implemented.voidremove(int pos) Removes the component at the specified index from this popup menu.voidRemoves aMenuKeyListenerfrom the popup menu.voidRemoves aPopupMenulistener.voidsetBorderPainted(boolean b) Sets whether the border should be painted.static voidsetDefaultLightWeightPopupEnabled(boolean aFlag) Sets the default value of thelightWeightPopupEnabledproperty.voidsetInvoker(Component invoker) Sets the invoker of this popup menu -- the component in which the popup menu is to be displayed.voidSets the popup menu's label.voidsetLightWeightPopupEnabled(boolean aFlag) Sets the value of thelightWeightPopupEnabledproperty, which by default istrue.voidsetLocation(int x, int y) Sets the location of the upper left corner of the popup menu using x, y coordinates.voidsetPopupSize(int width, int height) Sets the size of the Popup window to the specified width and height.voidSets the size of the Popup window using aDimensionobject.voidsetSelected(Component sel) Sets the currently selected component, This will result in a change to the selection model.voidSets the model object to handle single selections.voidsetUI(PopupMenuUI ui) Sets the L&F object that renders this component.voidsetVisible(boolean b) Sets the visibility of the popup menu.voidDisplays the popup menu at the position x,y in the coordinate space of the component invoker.voidupdateUI()Resets the UI property to a value from the current look and feel.Methods declared in class javax.swing.JComponentaddAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, unregisterKeyboardAction, updateMethods declared in class java.awt.Containeradd, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTreeMethods declared in class java.awt.Componentaction, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
- 
Constructor Details- 
JPopupMenupublic JPopupMenu()Constructs aJPopupMenuwithout an "invoker".
- 
JPopupMenuConstructs aJPopupMenuwith the specified title.- Parameters:
- label- the string that a UI may use to display as a title for the popup menu.
 
 
- 
- 
Method Details- 
setDefaultLightWeightPopupEnabledpublic static void setDefaultLightWeightPopupEnabled(boolean aFlag) Sets the default value of thelightWeightPopupEnabledproperty.- Parameters:
- aFlag-- trueif popups can be lightweight, otherwise- false
- See Also:
 
- 
getDefaultLightWeightPopupEnabledpublic static boolean getDefaultLightWeightPopupEnabled()Gets thedefaultLightWeightPopupEnabledproperty, which by default istrue.- Returns:
- the value of the defaultLightWeightPopupEnabledproperty
- See Also:
 
- 
getUIReturns the look and feel (L&F) object that renders this component.- Overrides:
- getUIin class- JComponent
- Returns:
- the PopupMenuUIobject that renders this component
 
- 
setUI@BeanProperty(hidden=true, visualUpdate=true, description="The UI object that implements the Component's LookAndFeel.") public void setUI(PopupMenuUI ui) Sets the L&F object that renders this component.- Parameters:
- ui- the new- PopupMenuUIL&F object
- See Also:
 
- 
updateUIpublic void updateUI()Resets the UI property to a value from the current look and feel.- Overrides:
- updateUIin class- JComponent
- See Also:
 
- 
getUIClassIDReturns the name of the L&F class that renders this component.- Overrides:
- getUIClassIDin class- JComponent
- Returns:
- the string "PopupMenuUI"
- See Also:
 
- 
processKeyEventProcesses key stroke events such as mnemonics and accelerators.- Overrides:
- processKeyEventin class- JComponent
- Parameters:
- evt- the key event to be processed
- See Also:
 
- 
getSelectionModelReturns the model object that handles single selections.- Returns:
- the selectionModelproperty
- See Also:
 
- 
setSelectionModel@BeanProperty(bound=false, expert=true, description="The selection model for the popup menu") public void setSelectionModel(SingleSelectionModel model) Sets the model object to handle single selections.- Parameters:
- model- the new- SingleSelectionModel
- See Also:
 
- 
add
- 
add
- 
add
- 
createActionComponent
- 
createActionChangeListenerReturns a properly configuredPropertyChangeListenerwhich updates the control as changes to theActionoccur.- Parameters:
- b- the menu item for which to create a listener
- Returns:
- a properly configured PropertyChangeListener
 
- 
removepublic void remove(int pos) Removes the component at the specified index from this popup menu.- Overrides:
- removein 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- posis greater than the number of items
- See Also:
 
- 
setLightWeightPopupEnabled@BeanProperty(bound=false, expert=true, description="Determines whether lightweight popups are used when possible") public void setLightWeightPopupEnabled(boolean aFlag) Sets the value of thelightWeightPopupEnabledproperty, which by default istrue. 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.- Parameters:
- aFlag-- falseto disable lightweight popups
- See Also:
 
- 
isLightWeightPopupEnabledpublic boolean isLightWeightPopupEnabled()Gets thelightWeightPopupEnabledproperty.- Returns:
- the value of the lightWeightPopupEnabledproperty
- See Also:
 
- 
getLabelReturns the popup menu's label- Returns:
- a string containing the popup menu's label
- See Also:
 
- 
setLabelSets 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:
 
- 
addSeparatorpublic void addSeparator()Appends a new separator at the end of the menu.
- 
insertInserts a menu item for the specifiedActionobject at a given position.- Parameters:
- a- the- Actionobject to insert
- index- specifies the position at which to insert the- Action, where 0 is the first
- Throws:
- IllegalArgumentException- if- index< 0
- See Also:
 
- 
insertInserts the specified component into the menu at a given position.- Parameters:
- component- the- Componentto insert
- index- specifies the position at which to insert the component, where 0 is the first
- Throws:
- IllegalArgumentException- if- index< 0
 
- 
addPopupMenuListenerAdds aPopupMenulistener.- Parameters:
- l- the- PopupMenuListenerto add
 
- 
removePopupMenuListenerRemoves aPopupMenulistener.- Parameters:
- l- the- PopupMenuListenerto remove
 
- 
getPopupMenuListenersReturns an array of all thePopupMenuListeners added to this JMenuItem with addPopupMenuListener().- Returns:
- all of the PopupMenuListeners added or an empty array if no listeners have been added
- Since:
- 1.4
 
- 
addMenuKeyListenerAdds aMenuKeyListenerto the popup menu.- Parameters:
- l- the- MenuKeyListenerto be added
- Since:
- 1.5
 
- 
removeMenuKeyListenerRemoves aMenuKeyListenerfrom the popup menu.- Parameters:
- l- the- MenuKeyListenerto be removed
- Since:
- 1.5
 
- 
getMenuKeyListenersReturns an array of all theMenuKeyListeners added to this JPopupMenu with addMenuKeyListener().- Returns:
- all of the MenuKeyListeners added or an empty array if no listeners have been added
- Since:
- 1.5
 
- 
firePopupMenuWillBecomeVisibleprotected void firePopupMenuWillBecomeVisible()NotifiesPopupMenuListeners that this popup menu will become visible.
- 
firePopupMenuWillBecomeInvisibleprotected void firePopupMenuWillBecomeInvisible()NotifiesPopupMenuListeners that this popup menu will become invisible.
- 
firePopupMenuCanceledprotected void firePopupMenuCanceled()NotifiesPopupMenuListenersthat this popup menu is cancelled.
- 
packpublic void pack()Lays out the container so that it uses the minimum space needed to display its contents.
- 
setVisibleSets the visibility of the popup menu.- Overrides:
- setVisiblein class- JComponent
- Parameters:
- b- true to make the popup visible, or false to hide it
- See Also:
 
- 
isVisible
- 
setLocationSets the location of the upper left corner of the popup menu using x, y coordinates.The method changes the geometry-related data. Therefore, the native windowing system may ignore such requests, or it may modify the requested data, so that the JPopupMenuobject is placed and sized in a way that corresponds closely to the desktop settings.- Overrides:
- setLocationin class- Component
- Parameters:
- x- the x coordinate of the popup's new position in the screen's coordinate space
- y- the y coordinate of the popup's new position in the screen's coordinate space
- See Also:
 
- 
getInvokerReturns the component which is the 'invoker' of this popup menu.- Returns:
- the Componentin which the popup menu is displayed
 
- 
setInvoker@BeanProperty(bound=false, expert=true, description="The invoking component for the popup menu") public void setInvoker(Component invoker) Sets the invoker of this popup menu -- the component in which the popup menu is to be displayed.- Parameters:
- invoker- the- Componentin which the popup menu is displayed
 
- 
showDisplays 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
 
- 
getComponentAtIndexDeprecated.replaced byContainer.getComponent(int)Returns the component at the specified index.- Parameters:
- i- the index of the component, where 0 is the first
- Returns:
- the Componentat that index
 
- 
getComponentIndexReturns the index of the specified component.- Parameters:
- c- the- Componentto find
- Returns:
- the index of the component, where 0 is the first; or -1 if the component is not found
 
- 
setPopupSizeSets the size of the Popup window using aDimensionobject. This is equivalent tosetPreferredSize(d).- Parameters:
- d- the- Dimensionspecifying the new size of this component.
 
- 
setPopupSize@BeanProperty(description="The size of the popup menu") public void setPopupSize(int width, int height) Sets the size of the Popup window to the specified width and height. This is equivalent tosetPreferredSize(new Dimension(width, height)).- Parameters:
- width- the new width of the Popup in pixels
- height- the new height of the Popup in pixels
 
- 
setSelected@BeanProperty(expert=true, hidden=true, description="The selected component on the popup menu") public void setSelected(Component sel) Sets the currently selected component, This will result in a change to the selection model.- Parameters:
- sel- the- Componentto select
 
- 
isBorderPaintedpublic boolean isBorderPainted()Checks whether the border should be painted.- Returns:
- true if the border is painted, false otherwise
- See Also:
 
- 
setBorderPainted@BeanProperty(bound=false, description="Is the border of the popup menu painted") public void setBorderPainted(boolean b) Sets whether the border should be painted.- Parameters:
- b- if true, the border is painted.
- See Also:
 
- 
paintBorderPaints the popup menu's border if theborderPaintedproperty istrue.- Overrides:
- paintBorderin class- JComponent
- Parameters:
- g- the- Graphicsobject
- See Also:
 
- 
getMarginReturns the margin, in pixels, between the popup menu's border and its containers.- Returns:
- an Insetsobject containing the margin values.
 
- 
paramStringReturns a string representation of thisJPopupMenu. 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 benull.- Overrides:
- paramStringin class- JComponent
- Returns:
- a string representation of this JPopupMenu.
 
- 
getAccessibleContextGets 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:
- getAccessibleContextin interface- Accessible
- Overrides:
- getAccessibleContextin class- Component
- Returns:
- an AccessibleJPopupMenu that serves as the AccessibleContext of this JPopupMenu
 
- 
processMouseEventThis method is required to conform to theMenuElementinterface, but it not implemented.- Specified by:
- processMouseEventin interface- MenuElement
- Parameters:
- event- a- MouseEventto be processed
- path- the path of the receiving element in the menu hierarchy
- manager- the- MenuSelectionManagerfor the menu hierarchy
- See Also:
 
- 
processKeyEventProcesses a key event forwarded from theMenuSelectionManagerand changes the menu selection, if necessary, by usingMenuSelectionManager's API.Note: you do not have to forward the event to sub-components. This is done automatically by the MenuSelectionManager.- Specified by:
- processKeyEventin interface- MenuElement
- Parameters:
- e- a- KeyEvent
- path- the- MenuElementpath array
- manager- the- MenuSelectionManager
 
- 
getSubElementsReturns an array ofMenuElements containing the submenu for this menu component. It will only return items conforming to theJMenuElementinterface. If popup menu isnullreturns an empty array. This method is required to conform to theMenuElementinterface.- Specified by:
- getSubElementsin interface- MenuElement
- Returns:
- an array of MenuElementobjects
- See Also:
 
- 
getComponentReturns thisJPopupMenucomponent.- Specified by:
- getComponentin interface- MenuElement
- Returns:
- this JPopupMenuobject
- See Also:
 
- 
isPopupTriggerReturns true if theMouseEventis considered a popup trigger by theJPopupMenu's currently installed UI.- Parameters:
- e- a- MouseEvent
- Returns:
- true if the mouse event is a popup trigger
- Since:
- 1.3
 
 
- 
Container.getComponent(int)