我在java swing应用程序中删除组件上的默认输入映射信息时遇到了一些麻烦。这就是我想要做的事情:
//List of keys to remove
public static final int[] OVERWRITTEN_KEYS =
{
VK_SPACE
};
//Get default input maps
InputMap[] im = {
(InputMap)UIManager.get("Button.focusInputMap"),
(InputMap)UIManager.get("ToggleButton.focusInputMap"),
(InputMap)UIManager.get("Slider.focusInputMap"),
(InputMap)UIManager.get("RadioButton.focusInputMap"),
(InputMap)UIManager.get("TextArea.focusInputMap"),
(InputMap)UIManager.get("TextField.focusInputMap")
};
//Loop through input maps
for(int i = 0; i < im.length; i++)
{
//Loop through keys
for(int j = 0; j < OVERWRITTEN_KEYS.length; j++)
{
if(im[i] != null)
{
//Overwrite press and release of button
im[i].put(KeyStroke.getKeyStroke(OVERWRITTEN_KEYS[j],0,false), "none");
im[i].put(KeyStroke.getKeyStroke(OVERWRITTEN_KEYS[j],0,true), "none");
}
}
}
但是,由于某种原因,这没有任何效果。按空格键仍然会触发JButton点击等。是否有人看到此代码块有问题?先谢谢。
答案 0 :(得分:8)
我无法再现您描述的问题。我通常修改组件的InputMap
,但UIManager
实例具有默认绑定。在下面的示例中,
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), NIL);
有效阻止 Space 键调用按钮的ActionListener
。取消注释行
button.getActionMap().put(NIL, nil);
将 Space 键与有效空操作相关联,如How to Make and Remove Key Bindings中所述的doNothing
操作所示。
/**
* @see http://stackoverflow.com/q/12133795/230513
*/
public class NilBindingTest extends JPanel {
private static final String NIL = "none";
private Action nil = new AbstractAction(NIL) {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("\"" + e.getActionCommand() + "\"");
}
};
private JButton button = new JButton(nil);
//private InputMap im = button.getInputMap();
private InputMap im = (InputMap) UIManager.get("Button.focusInputMap");
public NilBindingTest() {
this.add(new JButton("foo"));
System.out.println(Arrays.toString(im.keys()));
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), NIL);
//button.getActionMap().put(NIL, nil);
this.add(button);
}
private void display() {
JFrame f = new JFrame("NilBindingTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new NilBindingTest().display();
}
});
}
}