且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

摆动:将功能键(F2)设置为加速键

更新时间:2023-12-03 10:25:04

我知道这是一个旧线程,但是我在与原始海报完全相同的事情上苦苦挣扎,并找到了解决方案.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);

    }
}