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

1

10

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 :)

Cheslie answered 21/11, 2017 at 11:40 Comment(2)
I upvoted because this is something I've wondered about for a while, but haven't bothered to research. I can see why others might downvote this (there's no attempt), but it's interesting, programming-related, and shows that the OP has done some research.Aday
use KeyEvent in awt, with the same mechanism used in c#. Do your switch on detected KeyEvent. Let me know if you need more explanation, I'll add an answerCassiani
H
4

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.

Harriettharrietta answered 21/11, 2017 at 13:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.