Search code examples
javaswingnavigationkeyjmenu

How to navigate through java menu items with arrow keys (up/down)?


I have a menu with menu items. I programmatically select the menu and expand it:

// Create new menu with menu items
JMenu jMenuFile = new JMenu("File");
JMenuItem jMenuItemNew = new JMenuItem("New");
jMenuFile.add(jMenuItemNew );
JMenuItem jMenuItemOpen = new JMenuItem("Open");
menuFile.add(jMenuItemOpen);

// Select menu and expand it
jMenuFile.setSelected(true);                
jMenuFile.setPopupMenuVisible(true);

This code works fine, but I cannot navigate manually through the menu items with the arrow keys (up/down). How can this be achieved?

Note 1: If I set a mnemonic key (jMenuFile.setMnemonic ('D')), I get the focus and I can use the arrow keys. However, I don't want to use the mnemonic keys.

Note 2: jMenuFile.requestFocus() doesn't work either.


Solution

  • I have found the solution:

    jMenuDatei.doClick();
    

    This simulates a click on the menu. Therefore, it is selected and I can navigate through the menu items using the arrow keys.