The JPopupMenu Class

Popup menus were first introduced in AWT 1.1. These menus are not attached to a menubar; instead, they are free-floating menus that associate themselves with an underlying component. This component is called the invoker. Popup menus are brought into existence by a platform-dependent popup trigger event that occurs while the mouse is over the invoking component. In AWT and Swing, this trigger is typically a mouse event. Once raised, the user can interact with the menu normally. Figure 14.9 is an example of a popup menu in Swing.

A popup menu in Swing

Figure 14-9. A popup menu in Swing

You can add or insert JMenuItem, Component, or Action objects to the popup menu by calling the add() and insert() methods. The JPopupMenu class assigns an integer index to each menu item and orders them based on the layout manager of the popup menu. In addition, you can add separators to the menu by using the addSeparator() method; these separators also count as an index. Figure 14.10 shows the class diagram for the JPopupMenu component.

JPopupMenu class diagram

Figure 14-10. JPopupMenu class diagram

Displaying the Popup Menu

Popup menus are usually raised by invoking the show() method in conjunction with the platform-dependent popup trigger. The show() method sets the location and invoker properties of the popup before setting ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.