Zephyer Zephyer - 8 months ago 42
Java Question

Keypressed while a thread is running - how to capture the keys?

I have a

that contains a few other objects that do stuff. I will simplify the example by talking about some circle object (defined by circle class I made), and a square object (similar).

the circle moves randomly around the screen, while the square sits at its place. my intention is to move the square using the arrow buttons.
the current design is to have a thread with a while loop that contains a delay that sets the 'refresh rate' inside its run method.

I'm trying every method I know to capture the arrow keys and move the square around while the ball is running around the screen.

how do I capture keypresses (arrows for the example) so I can know where to move my square to?
I tried implementing
in the
but it didn't work. when I tried to use a
in the run, I got an exception.

please save me. :)


Thanks for that info. I would like further help to settle this issue -

lets say I have the following code:

this.getInputMap().put(KeyStroke.getKeyStroke("UP"), "actionName");
this.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "actionName");

new AbstractAction("actionName") {
public void actionPerformed(ActionEvent evt) {

how do I distinguish between UP and DOWN presses? what do I need to change?

Thanks! I'm a bit of a newbie, I know :)

Answer Source

KeyListener isn't designated for listening in Swing GUI, this Listener was builded for pre_historic AWT Component, these days so far away, use KeyBindings, this example can save your person