我正在尝试使用 UIManager 来获取和清除一些默认键绑定(bind),以便空格键不会激活我的 JButton,如 here 所述.问题是,可能是由于我的合成器外观和感觉,(InputMap)UIManager.get("Button.focusInputMap");
返回一个 null
。有谁知道以其他方式轻松清除组件输入映射的方法,或者为什么 UIManager 在这种情况下返回 null?感谢您提供任何提示,提前致谢。
最佳答案
首先:我喜欢装饰 StyleFactory 的想法,正如@David 在另一个答案中所建议的那样 :-) - 所以如果可行,建议使用那个方向。
无论如何,忍不住尝试一下:看起来 Nimbus(可能还有其他基于 Synth 的 LAF)在生命周期的早期非常需要这些默认值覆盖:他们只有在完成后才会接受它们在实际创建任何组件之前
// setting LAF
InteractiveTestCase.setLAF("Nimbus");
// tweak inputMap, immediately after setting the ui is fine
// uncomment the following line and it doesn't work
// new JPanel();
InputMap inputMap = (InputMap) UIManager.get("Button.focusInputMap");
inputMap.put(KeyStroke.getKeyStroke("SPACE"), "do-nothing");
如果此时 UIManager 未返回 inputMap,我会将其视为您的自定义 LAF 的不当行为,并会尝试进一步探究发生这种情况的原因。您可以尝试的另一件事是设置一个全新的 inputMap(这将具有在 LAF 切换中幸存下来的优势,因为它不是 UIResource,例如:
// setting LAF
InteractiveTestCase.setLAF("Nimbus");
// tweak inputMap, immediately after setting the ui is fine
InputMap inputMap = (InputMap) UIManager.get("Button.focusInputMap");
InputMap custom = new InputMap();
if (inputMap != null) {
// copy all bindings to custom
...
} else {
// add the binding we know of (as implementation detail)
custom.put(KeyStroke.getKeyStroke("released SPACE"), "released");
}
// overwrite the binding you want to change
custom.put(KeyStroke.getKeyStroke("SPACE"), "do-nothing");
// set the custom map
UIManager.put("Button.focusInputMap", custom);
关于java - 合成器外观中的默认按钮输入映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12464180/