tags:

views:

47

answers:

1

How do I write a code that loops while the LEFT or RIGHT arrow key is pressed?

+2  A: 

Add a KeyListener to your swing component (assuming you're using swing), and mark the keyDown and keyUp event. Specifically, on keyDown set a boolean for movingLeft, and on keyUp unset the boolean.

A better solution might be to use a map of enumerations of directions to booleans, to make the code cleaner.

Example:

Map<MoveDirection, Boolean> moveMap = new HashMap<MoveDirection,Boolean>();
moveMap.put( MoveDirection.LEFT, false );
moveMap.put( MoveDirection.RIGHT, false );
moveMap.put( MoveDirection.UP, false );
moveMap.put( MoveDirection.DOWN, false );

Then put and get as necessary.

Stefan Kendall
Well, if the app has a separate thread it can check the boolean, but if doesn't it has to create one (`new Thread() { public void run() { /* whatever */ } }.start();`) and that thread check the boolean flag (or something).
helios
I assume he's running on the event dispatching thread. The complexity of the question (or lack thereof), lead me to assume EDT + Swing as the environment.
Stefan Kendall
i'll try using KeyListener
Illes Peter
Note that the swing component has to have focus to receive keylistener events. For that reason, you may want to attach the keylistener to your JPanel (or JFrame)
Stefan Kendall