Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting and acting on keyboard direction keys in Java

G'day all,

I have a console project where it is intended the user presses the keyboard direction keys (non-numeric keypad) to move an avatar. I am having difficulty coding to check for the press of these keys. In Pascal it was easy enough to use "readkey" and code, for example, for #80 for the down keypress. However, I am stumped how to implement the same functionality in Java, though I think I understand the use of System.in and BufferedInputStream.

Could anyone help me out? Your thoughts or hints are much appreciated.

like image 278
elwynn Avatar asked Feb 21 '09 02:02

elwynn


People also ask

What key is pressed in Java keyboard?

Use KeyEvent. getKeyChar() and KeyEvent. getKeyCode() to find out which key the user pressed.

What method is used to receive data from the keyboard in Java?

Some ways to get data from the keyboardBufferedReader (and InputStreamReader) class. Scanner class. DataInputStream class.


1 Answers

The Console support issue in Java is well known, I am not sure that this is doable.

This was not initially possible with System.in since it used to work line-based.

Sun eventually added a java.io.Console class.

Here are its JavaDocs: http://java.sun.com/javase/6/docs/api/java/io/Console.html

Once you get the console (I think from System.console), you can get a reader and perhaps read characters from it, but I'm not sure if it includes keys.

Generally, you're supposed to use Swing or AWT if you want access to the keyboard, which is silly.

As of 2007, there was a feature request about it: here

like image 139
Uri Avatar answered Oct 17 '22 06:10

Uri