Java while ( keyispressed )
How do I write a code that loops开发者_高级运维 while the LEFT or RIGHT arrow key is pressed?
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.
精彩评论