The PopupMenu Class
One
of Swing’s nifty components is JPopupMenu, a
menu that automatically appears when you press the appropriate mouse
button inside of a component. (On a Windows system, for example,
clicking the right mouse button invokes a popup menu.) Which button
you press depends on the platform you’re using; fortunately,
you don’t have to care—Swing figures it out for you.
The care and feeding of JPopupMenu is basically
the same as any other menu. You use a different constructor
(JPopupMenu( )) to create it, but otherwise, you
build a menu and add elements to it the same way. The big difference
is you don’t need to attach it to a
JMenuBar. Instead, just pop up the menu whenever
you need it.
The following example, PopupColorMenu,
contains three
buttons. You can use a JPopupMenu to set the color
of each button or the frame itself, depending on where you press the
mouse. Figure 14.5 shows the example in action;
the user is preparing to change the color of the bottom button.

Figure 14-5. The PopupColorMenu application
//file: PopUpColorMenu.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PopUpColorMenu extends JFrame implements ActionListener { JPopupMenu colorMenu; Component selectedComponent; public PopUpColorMenu( ) { super("PopUpColorMenu v1.0"); setSize(100, 200); setLocation(200, 200); addWindowListener(new WindowAdapter( ) { public ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access