[Java] Making Fields Focusable in a JPopupMenu

Custom Swing popups are often created using a JPopupMenu. Some custom popups may contain input fields, such as a JTextField or a JSpinner. For these fields to be able to gain focus when the popup (or popup menu) is displayed, the invoker should be set prior to making it visible with setVisible. The invoker is usually the component that the user has to interact with in order to cause the popup to show. The invoker is set by calling the popup menu’s setInvoker.

Alternatively, the popup menu’s show can be used to set the invoker and display it at the same time. Note JPopupMenu has its own show method that is in addition to the one provided by java.awt.Component (which has been deprecated). The advantage with using JPopupMenu‘s show method is that it allows you to specify the location where it should popup relative to the location of the invoker. This reduces the need for your program to calculate where the popup should be displayed. In the following example, a popup is shown underneath a button whenever the button is clicked:

final JPopupMenu popup = new JPopupMenu();
popup.setLayout(new GridLayout(2, 2));
popup.add(new JLabel("Part 1: "));
popup.add(new JTextField(10));
popup.add(new JLabel("Part 2: "));
popup.add(new JTextField(10));

final JButton launcher = new JButton ();
launcher.setAction(new AbstractAction("Launcher")
    private static final long serialVersionUID = 1L;

    public void actionPerformed(ActionEvent e)
        popup.show(launcher, 0, launcher.getHeight());

As can be seen on line 17, we only need to retrieve the height of the button to always display the popup underneath it. Another advantage of using this method is that the popup will always try to keep all of the contents on the screen. If you tried moving the popup to the edge of the screen, it will try to move so that the entire contents of the popup will still appear on the screen


One Response to [Java] Making Fields Focusable in a JPopupMenu

  1. Jordan says:

    Very cool.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: