Java - Add accelerator to a JMenuItem
Asked Answered
M

2

1

I want to set an accelerator to a JMenuItem.

Right now I am setting it like this

openFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));

and it's working but I don't want ctrl+o as accelerator. I want 'space' as accelerator but I didn't find any method by which I can generate a KeyStroke corresponding to 'space'.

KeyStroke.getStroke()

either takes a char or (int, int). I didn't find any char corresponding to space also.

Mossy answered 15/4, 2012 at 8:48 Comment(0)
A
3

..didn't find any char corresponding to space also.

KeyEvent.VK_SPACE

I would not be surprised if Swing ignores it, since ' ' is an unusual & hard to see accelerator.

Apple answered 15/4, 2012 at 9:4 Comment(4)
I said I didn't find char corresponding to space. KeyEvent.VK_SPACE is an int and there is no method like KeyStroke.getStroke(int) which takes only int. I have to supply some modifier also which I don't want.Mossy
So let me get this straight. If the user tabs to a button and presses 'pace' to activate it, you want to invoke the menu action? Let me upgrade 'unusual & hard to see accelerator' to 'unworkable GUI'. My advice is 'choose a workable accelerator letter'. What is the text shown in the menu item?Apple
+1 for thinking of the user. :-) More here.Stunk
hmm ... didn't try just assuming: the display name is Space not empty :-)Polydeuces
S
3

Most UI delegates render a KeyEvent.VK_SPACE accelerator using something like the METRICAL TETRASEME: ⏘ (U+23D8). For example, an Action might include these lines:

static final int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, MASK));
Stunk answered 15/4, 2012 at 10:19 Comment(1)
Note that Mac OS X uses this accelerator to start a spotlight search.Stunk

© 2022 - 2024 — McMap. All rights reserved.