简体   繁体   中英

Java Swing: KeyBinding for KEY_TYPED event

I've been trying to learn keybinds by rewriting problems from my book that I've previously solved using KeyListener. The problem that I'm struggling to solve using keybinds requires me to record a message that's been typed and to display it on the panel.

The way it was solved using KeyListener is simply by recording characters with unicodes using the keyTyped() method and reading modifier/non-Unicode keys with keyPressed. If KeyEvent.VK_ENTER matches the keycode from the keyevent, then it displays the string on the panel.

~~~~~~~~

I thought that it can be solved in a similar way with KeyBinds. It says in the KeyEvent docs that KeyEvent.KEY_TYPED is fired every time a character is entered. I assumed that it meant every character with a corresponding Unicode being typed like how it works in KeyListener.

Later on, I realized that I have no idea how to retrieve the character since the Oracle tutorial on KeyBinds says that the KeyEvent is consumed when actionPerformed() is invoked.

This is the code that I THOUGHT would enable me to record typed keys to a StringBuilder using KeyBindings:

getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.KEY_TYPED, 0), "recordTypedKey");
getActionMap().put("recordTypedKey", addCharToString);

Is there a way to obtain the characters that would invoke KeyListener's keyTyped() method besides adding a key to every one of them and using a separate Action event to record them?

Is there a way to obtain the characters that would invoke KeyListener's keyTyped() method besides adding a key to every one of them and using a separate Action event to record them?

I do not believe there is a global KeyStroke you can pass to the InputMap that will work similar to a KeyListener, as KeyBindings work on an individual key basis. You can however create a single Action and bind keys to it by looping over the char values you wish to process - in the ActionListener implementation you can obtain the value of the key via getActionCommand . For example to deal with az:

AbstractAction action = new AbstractAction(){

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
    }

};
//loop over the ascii char values
for ( char a = 'A'; a <= 'Z'; a++ ){
     panel.getInputMap().put(KeyStroke.getKeyStroke(Character.toString(a)), "recordTypedKey");
}
panel.getActionMap().put("recordTypedKey", action);

You can add modifiers if needed...for example to deal with the shift key (eg upper case),

panel.getInputMap().put(KeyStroke.getKeyStroke("shift " + Character.toString(a)), "recordTypedKey");

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