Has anyone else had problems with getting KeyListener to work before? I mean, I set up the same class as a MouseListener (copy, paste) MouseMotionListener (copy, paste) KeyListener, and everything works except the KeyListener. Oh, and I did remember to the addKeyListener() line… ;).
any special circumstances?
-
is the KeyListener being added to a Window (the parent Frame consumes KeyEvents)?
-
is the frame in fullscreen? (i’ve had cases where KeyEvents would lag for a few seconds - and in some cases totally lock out!)
Adding a sleep() or yield to the render loop helps, so does lowering the Thread priority, but it doesn’t get rid of it all together.
[quote]any special circumstances?
- is the KeyListener being added to a Window (the parent Frame consumes KeyEvents)?
[/quote]
Nope, just to a JComponent, that is the CENTER of a BorderLayout in a JFrame. (the only other component is another JComponent that is the NORTH of the BL).
Nope.
I’m using less than 50% CPU, so I don’t believe it’s a thread-starvation problem.
Could it be something to do with the keyboard focus being on the “wrong” JComponent? I don’t touch focus at all, but I remember it used to be broken in strange ways (or perhaps under-documented, and then not behaving in ways that you might expect) in 1.2. Someone at Sun was telling me earlier this week that they’ve rewritten all the docs/tutorials etc covering focus, but the update might not go through for a while.
The answer is “yes”. The Swing tutorial is still waiting to be updated, but JComponent and JFrame do not automatically get keyboard focus - even though the application has the window focus. Experiments suggest that Java takes the kb focus (given to it by the window manager) and just creates a “keybaord blackhole” with a null FocusOwner.
The solution was for my custom JComponent to call requestFocus() on startup. Simple!