2010-12-17 87 views
6

JButtons认为按空格键与点击JButton(假设JButton具有我在此假设的焦点)相同。有没有办法关闭这种行为,让他们忽略按空格键?禁用空格键触发单击JButton

另外,更普遍的是,有没有一种技术可以做到这一点AbstractButtons

+0

我以为你的问题是关于按钮复数。有一些按钮与空格键一起使用,而有些则不是。那么为什么你要一次更换一个按钮呢? – camickr 2010-12-18 01:28:34

回答

1

您可以通过执行

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

禁用这似乎为其他AbstractButton的工作为好,如JRadioButton秒。

由于@camickr指出below可以一气呵成如下解决它所有JButton S:

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

谢谢你让我知道。答案已更新。 – aioobe 2017-05-13 13:19:28

3

通过aioobe给出的链接显示了如何做一个单独的按钮。如果您想要为所有JButton的做到这一点,你会怎么做:

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

如果你想为你做它需要重复上述每个不同的输入映射复选框,单选按钮。您可能想要阅读Enter Key and Button。它实际上与你想要的相反,因为它解释了在使用Enter键时如何调用按钮。但它可能有助于解释为什么此解决方案反向工作。