How to create shortcut to open a Jmenu?

Asked

Viewed 560 times

2

Speak guys, does anyone know how to create a keyboard shortcuts method to open a Jmenu. For example, click F1 or CTRL + "something" and open a screen.

  • 2

    http://answall.com/questions/55939/como-fechar-um-jframe-usando-eventos-do-teclado/55960#55960

  • Diegofm, gave it right there. Put as an answer to be able to vote for her!

  • 3

2 answers

1

Take this example, I think it will suit you:

JMenu actionMenu = new JMenu("Actions");
actionMenu.setMnemonic(KeyEvent.VK_A);

Where the menu will be accessed with the keys Alt+To

Att.

  • It didn’t work out Andrey France.

1


You can use the class KeyboardFocusManager to capture keyboard events and verify which was the event that triggered it:

KeyboardFocusManager
        .getCurrentKeyboardFocusManager()
        .addKeyEventDispatcher(new KeyEventDispatcher() {
          @Override
          public boolean dispatchKeyEvent(KeyEvent e) {
            System.out.println(e);
            if (e.getID() == e.KEY_RELEASED && e.getKeyCode() == KeyEvent.VK_F1) {
              jMenu1.setPopupMenuVisible(true);
              jMenu1.setArmed(true);
              return true;
            }
            return false;
          }
        });

In the example above the menu jMenu1 by pressing the button F1.

KeyboardFocusManager

The Keyboardfocusmanager is Responsible for Managing the active and focused Windows, and the Current Focus Owner. The Focus Owner is defined as the Component in an application that will typically receive all KeyEvents generated by the user.

In free translation:

Keyboardfocusmanager is responsible for managing the active and focused window, and the focus holder. The focus holder is defined as the component in the application that will typically receive all KeyEvents user-generated.


KeyEvents

An Event which indicates that a keystroke occurred in a Component.

In free translation:

An event that indicates which key was pressed into a component.

Reference: How to close a Jframe using keyboard events?

  • and if I want to use CTRL + some letter? I can do a Keyevent.VK_F1+ something ? I say this because it would increase my shortcut options.

  • 1

    Yes, if I’m not mistaken just add this to if: (e.getModifiers() & Keyevent.CTRL_MASK) != 0)

  • Opa, gave ! You could explain to me the function of this line ? for me to understand well what she is doing. if (e. getID() == e.KEY_RELEASED && e.getKeyCode() == KeyEvent.VK_A && (e. getModifiers() & KeyEvent.CTRL_MASK) != 0)

  • 1

    Yes. The first part is to check the type of Event, which in this case is Key Released (i.e., when you release the key). The second part checks if the pressed key is what you want, in the case "A". The third part checks if there is any function key (such as Shift, CTRL or Alt) pressed together.

  • Very good, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.