How to implement basic arrow movement in console window using java?

I am struggling to find a way to implement basic moving with an arrow in the console window. I came across a C # script that just uses a switch statement and some variables, but my teacher insists on using Java.

From some other threads, the answers all seemed to say that this is not possible in Java unless you install certain (correct me if they are wrong) frameworks like JNA and / or Jline, but as a beginner, I have no idea I have, things even mean.

Now, before you say that my teacher is an idiot, thinking that we can do this, he never said that this should be a movement with arrows, I just thought it would be cool :)

+5
source share
1 answer

This is more complicated than it seems, mainly due to the way Java works on different platforms. The main solution for reading from the keyboard is to use stdin, for example:

InputStream in = System.in; int next = 0; do { next = in.read(); System.out.println("Got " + next); } while (next != -1); 

Now there are two problems:

  • On unix platforms, this will not print the next character as soon as it has been pressed, but only after the return button has been pressed, since the operating system buffers the default input
  • There is no ascii code for the arrow keys, instead there are so-called escape sequences that depend on the terminal emulator used, so on my Mac, if I run the above code and press Arrow-Up and then key returns, I get the following output:

     Got 27 // escape Got 91 Got 65 Got 10 // newline 

There is no good platform-independent, independent way, if you only target unix platforms, javacurses can help.

+3
source

Source: https://habr.com/ru/post/1273544/


All Articles