MenuSelectionManager.defaultManager () is really a good solution, but it will not work if you try to pre-select the JPopupMenu submenu (it will hide the parent menu). In addition, this will ruin other keyboard navigation behaviors (you cannot press left to hide submenus, etc.)
Unfortunately, in Swing there is no good solution for this question ... My solution is ugly, but unfortunately this work is perfect:
public static void setMenuSelectedIndex(final JPopupMenu popupMenu, final int index) { SwingUtilities.invokeLater(new Runnable(){public void run() { for (int i=0; i < index+1; i++) { popupMenu.dispatchEvent(new KeyEvent(popupMenu, KeyEvent.KEY_PRESSED, 0, 0, KeyEvent.VK_DOWN, '\0')); } }}); }
As you can see, I basically mimic the "Down" Key-Key-Presses on a pop-up menu ...
The best solution might not be to simulate VK_DOWN hardcodedly, but to read a pop-up input map and determine which KeyCode means "select the next menu item" - but I think most of us would agree with this hack ...
You can also look at this method, which selects a menu item after selecting it. It uses the previous method.
public static void setSelectedIndexWhenVisible(final JMenu menu, final int index) { menu.getPopupMenu().addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { PopupUtils.setMenuSelectedIndex(menu.getPopupMenu(), index); menu.getPopupMenu().removePopupMenuListener(this); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } @Override public void popupMenuCanceled(PopupMenuEvent e) { } }); }
Eyal katz
source share