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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Amit
  • 33,847
  • 91
  • 226
  • 299

2 Answers2

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 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. – Amit Apr 15 '12 at 09:10
  • 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? – Andrew Thompson Apr 15 '12 at 09:38
  • 1
    +1 for thinking of the user. :-) More [here](http://stackoverflow.com/a/10161155/230513). – trashgod Apr 15 '12 at 10:20
  • 1
    hmm ... didn't try just assuming: the display name is _Space_ not empty :-) – kleopatra Apr 15 '12 at 10:50
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));
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    Note that Mac OS X uses this accelerator to start a [spotlight search](http://en.wikipedia.org/wiki/Spotlight_%28software%29). – trashgod Apr 15 '12 at 10:26