0

如何更改此代码以接受任何键(不仅是 F5)并打印该键?

component.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "F5 Pressed");
component.getRootPane().getActionMap().put("F5 Pressed", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Code here
    }
});
4

2 回答 2

2

我如何(“cahnhe”)这个代码来接受任何键(不仅是 F5)并打印键?

于 2013-08-06T13:45:15.597 回答
1

用于KeyboardFocusManager注册KeyEventDispatcher

KeboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {       
    @Override
    public boolean dispatchKeyEvent(KeyEvent ke) {
        if (yourComponent.hasFocus && ke.getID == KeyEvent.KEY_TYPED) {
            // Your code here
            // Use ke.getKeyChar() to detect which key was pressed.
        }
    }
}
于 2013-08-06T14:40:39.093 回答