I want to write a Snake game in Java. How can I continuously monitor input and if user pressed W
set variable
Char lastDirection = 'w'; //hence, Direction.UP
?
I know about the Scanner
method: Scanner scan= new Scanner(System.in);
...
But then user would have to hit enter each time he presses the button. Document Listener (Swing) seems better, but then i would have a long string of user input saved somewhere that I don't need. What is the right method for listening to keyboard and remembering the last character?
Answer to the "possible duplicate" question is irrelevant, because I was looking for a Swing compatible method, not a Console API. My question was probably marked as a "possible duplicate" using grep utility triggered by a keyword Scanner
.
KeyAdapter
works well with Swing components for this task.
http://zetcode.com/tutorials/javagamestutorial/snake/