开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜