Java Swing: Can I set a button mnemonic that doesn't require pressing alt?
Asked Answered
A

3

7

For example, say I have a series of toolbar-style buttons across the top of my application's main window. I want to attach a mnemonic to one of these that's just a single keypress, like F3.

When you set the mnemonic to KeyEvent.VK_F3, the user has to press Alt+F3.

If you have a menu item, you can set an accelerator, rather than a mnemonic, and choose whether to use a meta key. Buttons don't let you set an accelerator, however.

Is there a way to turn of the meta-key for button mnemonics?

Aweigh answered 2/3, 2010 at 22:10 Comment(0)
Z
4

Actions can bind a chunk of code to a menu item, a keystroke, a button and anything else you are interested.

In general, don't think of your code as tied to a specific keypress/event--and don't use anonymous inner classes. Instead use real classes where your code can be reused for different types of things. That pattern used by the Action class gives some good examples of this.

Zennie answered 2/3, 2010 at 22:13 Comment(0)
C
3

Well behind the scenes, whether you use an accelerator or a mnemonic on a component, the method will create a Key Binding for you.

So there is nothing to prevent you from binding a KeyStroke and Action to whatever component you want and manually create the Key Binding. It can even be a component that doesn't have the setMNemonic(...) method.

Calvo answered 2/3, 2010 at 23:29 Comment(0)
S
0

Are you sure that accelerators cannot be defined on buttons if the button was configured using an Action? (I know this was true at one point, but I thought this may be different in later versions of Java.)

In any event, here is another method to set it on a button:

button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(myKeyStroke, "actionName");
button.getActionMap().put("actionName", myAction);

Where myKeyStroke is a keystroke such as F3, "actionName" is a label (String), and myAction is the action it invokes.

Silicon answered 3/3, 2010 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.