2010-12-17 36 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鍵時如何調用按鈕。但它可能有助於解釋爲什麼此解決方案反向工作。