Search code examples
javaswingjava-ioroguelike

Using KeyStroke for input, is there an easier way of reading A - Z keys?


First of all, this isn't for a keylogger, it's for an input in a roguelike game where the JLabel in my JFrame will say "Name: " and I want to be able to type A-Za-z. After having a look at lots of options for key input, I am back where I started using KeyStrokes and Actions.

What I am wondering is whether there is a way to add a range of keys, rather than repeating this 56 times:

Action a = new AbstractAction() {

    public void actionPerformed(ActionEvent e) {
        // add a to string
    }
};
getInputMap().put(KeyStroke.getKeyStroke("a"), "a");
getActionMap().put("a", a);

I mean, I could do it this way, just write a bit of copy and pasting, but I really do hate that. There has to be a more elegant solution than using KeyListener which isn't very good as it means I have to somehow have focus but my window is simply one JFrame with a big JLabel in it.

Also, I've only been doing java a few days now, so that's why I am probably missing the a very commonly known solution, but if there is one, please do share! Appreciated.


Solution

  • I am using a content manager class which treats each "screen" as a JPanel which is set as the content pane, I put a reference to the parent JFrame into the base "screen" class and then added a KeyListener to the parent JFrame. This captures input just how I want it to. I didn't do this before as I mistakenly added the KeyListener to the content pane. It all appears to work fine now.

    public void run() {
        this.getParent().addKeyListener(new KeyListener() {
    
            public void keyPressed(KeyEvent e) {
                appendLabel(e.getKeyChar());
            }
    
            public void keyReleased(KeyEvent e) { }
            public void keyTyped(KeyEvent e) { }
        });
    }
    

    Thanks @millimoose!