8

JButtons consider pressing the space bar to be the same as clicking on the JButton (assuming the JButton has the focus, which I am assuming here). Is there a way to turn off this behavior so they ignore pressing the space bar?

Also, more generally, is there a technique for doing this with AbstractButtons?

aioobe
  • 413,195
  • 112
  • 811
  • 826
Paul Reiners
  • 8,576
  • 33
  • 117
  • 202
  • I thought your question was about buttons plural. It is not a very good UI to have some buttons work with the space bar and some not. So why would you want to change buttons one at a time? – camickr Dec 18 '10 at 01:28

4 Answers4

3

The link given by aioobe shows how to do it for an individual button. If you want to do this for all JButton's you would do:

InputMap im = (InputMap)UIManager.get("Button.focusInputMap");
im.put(KeyStroke.getKeyStroke("pressed SPACE"), "none");
im.put(KeyStroke.getKeyStroke("released SPACE"), "none");

If you want to do it for check boxes and radio buttons you would need to repeat the above for each different input map.

You may want to read Enter Key and Button. It actually does the opposite of what you want since it explains how to invoke the button when the Enter key is used. But it may help explain why this solution works in reverse.

camickr
  • 321,443
  • 19
  • 166
  • 288
2

You can disable it by doing

jbutton.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "none");

This seems to work for other AbstractButtons as well, such as JRadioButtons.

As @camickr points out below you can solve it for all JButtons in one go as follows:

InputMap im = (InputMap)UIManager.get("Button.focusInputMap");
im.put(KeyStroke.getKeyStroke("pressed SPACE"), "none");
im.put(KeyStroke.getKeyStroke("released SPACE"), "none");
Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

Spacebar on keyup may activate last focused element. To defocus the element try:

${element}.blur()
Richard Z
  • 161
  • 2
  • 3
0

use:

button.setFocusable(false)

this way, the button can only be clicked using the mouse and not the space bar.

Debil.exe
  • 11
  • 1
  • 3