我正在使用 F10 作为将数据更新到数据库的快捷方式。每当我按 F10 更新工作正常但是。我的焦点移动到菜单栏(该栏包含关闭,最小化、最大化)有没有办法阻止它?我知道这是 Windows 快捷方式。有可能阻止它吗?
最佳答案
您可以尝试从 JMenuBar
中删除 WHEN_IN_FOCUSED_WINDOW
操作。只需将这一行添加到您的代码中:
menuBar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F10"), "none");
menuBar
是您的 JMenuBar
组件的引用。
编辑:
确实,如果您不使用 JMenuBar
,上述解决方案将不起作用。另一种解决方案是创建一个空操作并使用它来绑定(bind) F10
键。 (参见 [键绑定(bind)][1])。
这是一个例子:
//create an empty action which do nothing
Action emptyAction = new AbstractAction(){
public void actionPerformed(ActionEvent e)
{ //do nothing here }};
//bind F10 with the empty action
KeyStroke f10 = KeyStroke.getKeyStroke( "F10");
frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(f10, "F10");
frame.getRootPane().getActionMap().put("F10", emptyAction);
frame
是您的 JFrame
组件。
[1]: https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
关于java - 需要在swing小程序中禁用F10键的Frame Focus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27428196/