如何使用Java在控制台窗口实现基本的箭头键移动?

10

我正在努力寻找一种在控制台窗口实现基本箭头键移动的方法。我已经找到了一个使用switch语句和一些变量的C#脚本,但我的老师坚持使用Java。

从其他线程中得出的答案似乎都表明,在Java中不可能实现,除非安装某些(如果我错了,请纠正我)像JNA和/或Jline这样的“框架”,但作为初学者,我甚至不知道那些东西是什么。

在你说我的老师是白痴之前,他从来没有说过必须要有箭头键移动,我只是觉得这很酷 :)


3
我点赞了,因为这是我长期以来一直想知道却没有费心去研究的事情。我能理解为什么其他人可能会踩这个帖子(因为没有尝试解决问题),但它很有趣、与程序设计相关,并且显示出发帖者已经做了一些研究。 - byxor
在awt中使用KeyEvent,使用与c#相同的机制。根据检测到的KeyEvent执行switch操作。如果需要更多解释,请告诉我,我会提供答案。 - Ahmad Sanie
1个回答

4
这比看起来要困难得多,主要是因为Java在不同平台上的工作方式不同。从键盘读取输入的基本解决方案是使用stdin,像这样:
    InputStream in = System.in;

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

现在,有两个问题:

  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
    

如果你只针对Unix平台,那么在这方面没有一个好的跨平台解决方案,javacurses 可以提供帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接