Detecting and operating keyboard keys in Java

G'day all

I have a console project where it is assumed that the user presses the direction keys of the keyboard (non-numeric keyboard) to move the avatar. I am having difficulty coding to test these keystrokes. In Pascal, it was easy enough to use the โ€œread keyโ€ and code, for example, for # 80 to press a key. However, I donโ€™t understand how to implement the same functionality in Java, although I think I understand the use of System.in and BufferedInputStream.

Can anyone help me out? Your thoughts or hints are greatly appreciated.

+9
java key keyboard direction
Feb 21 '09 at 2:42
source share
4 answers

The console support issue in Java is well known, I'm not sure if this is doable.

Initially, this was not possible with System.in, since it used to work on a string basis.

As a result, Sun added the java.io.Console class.

Here is 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 the reader and possibly read the characters from it, but I'm not sure if it includes the keys.

Generally, you should use Swing or AWT if you want to access the keyboard, which is stupid.

As of 2007, there was a request for this: here

+4
Feb 21 '09 at 2:50
source share

Unfortunately, this is not possible in portable mode:

http://forums.sun.com/thread.jspa?threadID=5351637&messageID=10526512

On Windows, reading from System.in will be blocked until you press enter , even if you are not using BufferedReader . Arrows will cycle through the history of teams. Try it yourself:

 import java.io.*; public class KeyTest { public static void main(String[] argv) { try { InputStreamReader unbuffered = new InputStreamReader(System.in); for (int i = 0; i < 10; ++i) { int x = unbuffered.read(); System.out.println(String.format("%08x", x)); } } catch (Exception e) { System.err.println(e); } } } 

The same problem with using the Console class (the input is buffered under Windows, the arrow keys set by Windows):

 import java.io.*; public class KeyTest2 { public static void main(String[] argv) { try { Console cons = System.console(); if (cons != null) { Reader unbuffered = cons.reader(); for (int i = 0; i < 10; ++i ) { int x = unbuffered.read(); System.out.println(String.format("%08x", x)); } } } catch (Exception e) { System.err.println(e); } } } 
+5
Feb 21 '09 at 2:57
source share

If java.io.console does not work for you (I have not tried this), try JLine . I used this to solve a vaguely similar problem .

+5
Feb 21 '09 at 18:38
source share

Not with embedded Java code. Check out the java curses or JLine libraries as mentioned above if you want to continue.

0
Jul 24 '18 at 1:53
source share



All Articles