1

I have a class that has a KeyListener class nested into it, but the event doesn't seem to register. I am pretty new to Java, so i might be doing something completely wrong...

This is the code:

    public class CaesarFrame extends JFrame{
        ...
        private JTextField jtf1 = new JTextField(20);
        ...
        jtf1.addKeyListener(this.new InputFieldKeyListener());
        ...
        class InputFieldKeyListener extends KeyAdapter{
                public void keyTyped(KeyEvent e) {
                    System.out.println(e.toString());
                }
        }
    }

Thanks for the help!

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Zsipgun
  • 29
  • 6

2 Answers2

3

Do you need this.new ... when adding the KeyListener? Can you try omitting this. and just putting:

jtf1.addKeyListener(new InputFieldKeyListener());

Also, not sure what you're trying to do precisely, but make sure you're using the proper event. Your JTextField might be generating keyPressed or keyReleased events when you think it will be keyTyped.

I would override those two additional events the same way you did keyTyped, and see what output you get. That might be all there is to it.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • Thanks for your suggestions! The two other events don't fire either, and omitting the `this` doesn't seem to change it. I have a JButton in there with a similarly declared ActionListener, and that works well, so its a bit odd, but I must be overlooking something... – Zsipgun Oct 24 '11 at 22:41
  • (1) *Immediately* after the line adding the KeyListener, if you call `System.out.println(jtf1.getKeyListeners().length)` does it print something other than `0`, and/or do you get a NullPointerException? (2) After adding the KeyListener, are you perhaps accidentally re-declaring `jtf1`, and therefore creating a new object, with an empty set of KeyListeners? – jefflunt Oct 24 '11 at 23:14
2

"To fire keyboard events, a component must have the keyboard focus."—How to Write a Key Listener. Alternatively, consider key bindings, examples of which may be found in the answers to this question.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045