摆动:将功能键(F2)设置为加速键
我有一个菜单项重命名",为此将F2设置为加速器.确实,显示菜单时,在重命名"旁边会显示一个小"F2"指示.
I have a menu item, "rename", for which F2 is set as an accelerator. Indeed when the menu is displayed there a little "F2" indication next to "rename".
遗憾的是,这不起作用.该加速器不会触发任何响应.当我将加速器更改为CTRL + F2时,它将起作用.
Sadly, this does not work. This accelerator triggers no response. When I change the accelerator to CTRL+F2 - it works.
似乎我应该使用InpoutMpa/ActionMap.这样做的问题是我希望它可以在应用程序中的任何地方工作,因此我试图将其与顶级JFrame关联.但是,JFrame没有getInputMap()方法.
It seems that I should use an InpoutMpa/ActionMap. The problem with that is that I want this to work everywhere in the app so I am trying to associate it with the top-level JFrame. But, JFrame does not have a getInputMap() method.
迷失了.
[已添加]
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
JMenuItem mi = new JMenuItem("Rename");
mi.setAccelerator(ks);
mi.addActionListener(action);
我知道这是一个旧线程,但是我在与原始海报完全相同的事情上苦苦挣扎,并找到了解决方案.JFrame本身没有getInputMap方法,但其根窗格却有.因此,您必须改为使用"getRootPane.getInputMap".
I know this is an old thread, but I struggled with the exact same thing as the original poster and found the solution. The JFrame itself doesn't have a getInputMap method, but its root pane does. So you have to use "getRootPane.getInputMap" instead.
示例代码:
public class ApplicationFrame extends JFrame {
private AbstractAction f2Action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
// Do something useful
}
};
public ApplicationFrame() {
InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getRootPane().getActionMap();
inputMap.put(KeyStroke.getKeyStroke("F2"), "f2Action");
actionMap.put("f2Action", f2Action);
}
}