Search code examples
javaswingjmenupopup

How to select first item in JPopupMenu?


In the past, when one made a JPopupMenu visible it's first item would get selected by default: http://weblogs.java.net/blog/alexfromsun/archive/2008/02/jtrayicon_updat.html

Nowadays the default behavior is to pop up the menu without any item selected. I would like create a JPopupMenu with a single item that will pop up selected and centered under the mouse pointer. I have managed to get the item to pop up centered under the mouse but I the JMenuItem refuses to render as if it is selected. If I move the mouse out of the item and back in it selects properly.

Any ideas?

Here is my testcase:

import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

public class Test extends JFrame
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.getContentPane().addMouseListener(new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent e)
            {
                if (e.isPopupTrigger())
                    popupTriggered(e);
            }

            @Override
            public void mouseReleased(MouseEvent e)
            {
                if (e.isPopupTrigger())
                    popupTriggered(e);
            }

            private void popupTriggered(MouseEvent e)
            {
                JPopupMenu menu = new JPopupMenu();
                final JMenuItem item = new JMenuItem("This is a JMenuItem");
                menu.add(item);
                Point point = e.getPoint();
                int x = point.x - (item.getPreferredSize().width / 2);
                int y = point.y - (item.getPreferredSize().height / 2);
                menu.show((Component) e.getSource(), x, y);
            }
        });
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
    }
}

Solution

  • Nowadays the default behavior is to pop up the menu without any item selected.

    Actually, I would argue that this is the correct behavior, at least in Windows. Other non-Java applications do this too. I don't think it's worth breaking this convention even if there is only one item in the menu. If you feel otherwise, you can set the selection index as in sean.bright's answer.


    So, I finally got the chance to try it out on Java 1.6.0_11, and found some inconsistent behavior: If the popup menu juts out of the parent frame, the item is automatically selected; if the popup menu appears entirely within the parent frame, nothing is selected. Sounds like a Swing bug, which at least warrants an RFE for consistent behavior.