1

I have a JPanel 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 keylistener in the jpanel but it didn't work. when I tried to use a KeyEvent in the run, I got an exception.

please save me. :)

EDIT:

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");

  this.getActionMap().put("actionName",
            new AbstractAction("actionName") {
                public void actionPerformed(ActionEvent evt) {
                   //dostuff
        }
     }
);

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 :)

Lahiru Ashan
  • 767
  • 9
  • 16
Zephyer
  • 333
  • 6
  • 16
  • Please edit your question to show the exception text and the first couple lines of the stack trace. – Gray Feb 23 '12 at 18:03
  • Use KeyEventDispatcher: http://stackoverflow.com/questions/286727/java-keylistener-for-jframe-is-being-unresponsive (second answer) – kajacx Feb 23 '12 at 18:34

1 Answers1

2

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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319