简体   繁体   中英

Java: How to change activation event key for setDefaultButton()?

Is there a way to change the default activation event key for setDefaultButton()? The default key is ENTER .

This is the scenario: In login window, there's two(2) button, one is for login and the other is exit. Setting login button to setDefaultButton() is a good idea but I would like to have another activation event key which is ESCAPE to respond with exit button.

Thanks!

this is what you should do

InputMap inputMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "exitAction");
panel.getActionMap().put("exitAction", exitAction);

Action exitAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            //what ever happen on exit goes here
        }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM