开发者

Java while ( keyispressed )

开发者 https://www.devze.com 2022-12-16 18:20 出处:网络
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 ev

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

精彩评论

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