JFrame - 读取两次击键(ESC和F2)并执行不同的操作

时间:2013-07-26 08:36:38

标签: java swing focus jframe key-bindings

我想要识别ESC和F2键的两次击键。下面是我按下退出键时的识别方式:

// Enable escape to close the window by first returning the rootPane object for this frame, then the InputMap that is usedduring condition i.e. JComponent.WHEN_IN_FOCUSED_WINDOW
    // and then use function put to add a binding for keyStroke to actionMapKey
    frame.getRootPane().getInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");

    // Kill the AuotIt script when closing the window by first returning the rootPane object for this frame then the ActionMap used to determine what Action 
    // to fire for particular KeyStroke binding. The returned ActionMap, unless otherwise set, will have the ActionMap from the UI set as the parent.
    frame.getRootPane().getActionMap().put("Cancel", new AbstractAction(){
        public void actionPerformed(ActionEvent x) {
            // Undertake some action here
        }
    });

我尝试了完全相同的事情但是将关键事件更改为F2但是当我按下F2按钮时没有任何反应。以下是我尝试识别F2的方法:

frame.getRootPane().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "pressed");

    // 
    frame.getRootPane().getActionMap().put("pressed", new AbstractAction(){
        public void actionPerformed(ActionEvent x) {

            // Change the hasusersetcomport flag in hasusersetcomport.txt to 0
            notifyScriptThatUserNeedsCOMPorts("0");

            // Notify Script That User Pressed Allow Pairing (which is the default setting for wasallowpairingpressed.txt) 
            notifyScriptThatUserPressedAllowPairing("1");

            // Write menu Item Event Control ID
            RFC95.writeMenuItemEventControlID("8");

            // Write empty string into config file
            writeUserSelectedCOMportIntoConfigFile("");

            // Notify user that current pairing has been deleted
            notifMssgLabel.setText("<html><p>CURRENT PAIRING SETTING DELETED. WINDOW CLOSING</p></html>");
            notifMssgLabel.setForeground(officialSuccessFontColour);
            notifMssgLabel.setFont(officialFontBold);

            // Change the hasusersetcomport flag in hasusersetcomport.txt to 0
            notifyScriptThatUserNeedsCOMPorts("0");

            panelTimer.start();
        }
    });

关于我遇到问题的原因。

感谢。

0 个答案:

没有答案