Question

I try to make my JMenuBar to activate first JMenu on Alt KeyEvent, but without opening popup, so that one could open popup with arrows keystrokes later. Just like it is done in NetBeans, Mozilla, any other program window.

Here is the code that works not as intended. The worst side effect is that it reacts on alt+tab combination, and it definitely should not popup menu on alt+tab. I just need to make a menu go to the "armed" state and be able to traverse menus by arrow keys (arrows right & left to "arm" menus and arrow down to open "armed" menu popup). Is there any simple way to make this happen?

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

public class Test5 extends JFrame {

    public Test5() {
        super("test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel pan = new JPanel(new BorderLayout());

        final JMenuBar bar = new JMenuBar();
        final JMenu menu = new JMenu("File", false);

        menu.setMnemonic(KeyEvent.VK_ALT);

        JMenuItem item = new JMenuItem("All");
        JMenuItem item2 = new JMenuItem("Exit");
        menu.add(item);
        menu.add(item2);

        JMenu menu1 = new JMenu("Test");
        JMenuItem item1 = new JMenuItem("All");
        menu1.add(item1);

        bar.add(menu);
        bar.add(menu1);

        setJMenuBar(bar);

        setSize(200, 200);
        setVisible(true);
    }


    public static void main(String[] args) {
        new Test5();
    }

}

Solved thanks to Guillaume Polet: There is some code in com.sun.java.swing.plaf.windows.WindowsLookAndFeel class, wich works with Alt keystrokes:

public void initialize() {
    super.initialize();
    // some more initialization here
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
                        .addKeyEventPostProcessor(WindowsRootPaneUI.altProcessor);
}

And the AltProcessor class does all the magic.

If you don't have any custom LaF, you can just use WindowsLookAndFeel as it is, or there is proper example how to process Alt events in menus for your own special LaF.

Was it helpful?

Solution

Before starting your GUI, invoke this line:

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

And remove the mnemonic.

This will automatically install the desired behaviour on Windows. If you need this on all platforms, then you will have to go with KeyBindings, but since this behaviour is only observed on Windows, I don't find it problematic to recreate it only on Windows.

OTHER TIPS

no idea why, but about answering the question

  • 1st step

    1. have to use KeyBindings and with output to the Swing Action (adviced) or ActionListener

    2. there are two methods menu.setArmed(true) or menu.setSelected(true)

  • but in both cases JMenu is selected forever then to required 2nd. step to add MenuListener and restore previous selected or armed to false

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top