Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

Pop-Up Menus

One of Swing’s nifty components is JPopupMenu, a context menu that appears at the mouse location when you press the appropriate mouse button or keystroke. (On a two-button mouse, clicking the right mouse button invokes a pop-up menu. On a single-button Mac, you Command-click.) Which button you press depends on the platform you’re using; fortunately, from the code’s point of view 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 that you don’t attach it to a JMenuBar. Instead, just pop up the menu whenever and wherever you need it. Prior to Java 5.0, this process is a little cumbersome; you have to register to receive the appropriate mouse events, check them to see if they are the pop-up trigger and then pop the menu manually. With Java 5.0, the process is simplified by having components manage their own pop-up menus.

First, we’ll show an example of explicit pop-up handling. The following example, PopupColorMenu, contains three buttons. You can use a JPopupMenu to set the color of each button or the background frame itself, depending on where you click the mouse.

    //file: PopUpColorMenu.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class PopUpColorMenu implements ActionListener
    {
      Component selectedComponent;

      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.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content