Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

java - Swing: Setting a function key (F2) as an accelerator

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".

Sadly, this does not work. This accelerator triggers no response. When I change the accelerator to CTRL+F2 - it works.

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.

Lost.

[Added]

     ks = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
     JMenuItem mi = new JMenuItem("Rename");
     mi.setAccelerator(ks);
     mi.addActionListener(action); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Example code:

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);

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...