Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement basic arrow-key movement in the console window with java? [duplicate]

I'm struggling with trying to find a way to implement basic arrow-key movement in a console window. I have come across a C# script which simply uses a switch statement and some variable's, but my teacher insists on using Java.

From some other threads the answers all seemed to say that it's not possible in Java unless you install certain (correct me if im wrong) "frameworks" like JNA and/or Jline, but as a beginner i have no idea what those things even mean.

Now before you say my teacher is an idiot for thinking we could do that, he never said it had to be arrow-key movement, i just thought it'd be cool :)

like image 873
Thomas Linssen Avatar asked Nov 21 '17 11:11

Thomas Linssen


People also ask

How do you type an arrow in Java?

When more than one parameter is passed, they are separated by commas. To support lambdas, Java has introduced a new operator “->”, also known as lambda operator or arrow operator. This arrow operator is required because we need to syntactically separate the parameter from the body.

How do I use arrow keys in JavaScript?

To detect the arrow key when it is pressed, use onkeydown in JavaScript. The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.

What are the 4 arrow keys?

Cursor control keys ) and Home, PgUp, End, PgDn. The arrows are known as cursor control keys (the cursor is the flashing bar on the computer screen that shows your current position). Many keyboards also have a separate pad for these keys (look for a set of arrow keys).


1 Answers

This is more difficult than it appears, mostly because of the way Java works across platforms. The basic solution to read from the keyboard is to use stdin, like so:

    InputStream in = System.in;

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

Now, there are a two problems:

  1. On unix platforms this will not print the next character as it is pressed but only after return has been pressed, because the operating system buffers the input by default
  2. 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 hit Arrow-Up and then the return key I get the following output:

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

There is no good platform independent way around this, if you are only targetting unix platforms, javacurses might help.

like image 167
Felix Leipold Avatar answered Sep 19 '22 20:09

Felix Leipold