在 Java 中检测和操作键盘方向键

2022-01-13 00:00:00 keyboard key java direction

万事如意,

我有一个控制台项目,旨在让用户按下键盘方向键(非数字键盘)来移动头像.我很难编码来检查这些键的按下情况.在 Pascal 中,使用readkey"和代码很容易,例如,#80 用于向下按键.然而,我很难理解如何在 Java 中实现相同的功能,尽管我认为我了解 System.in 和 BufferedInputStream 的使用.

I have a console project where it is intended the user presses the keyboard direction keys (non-numeric keypad) to move an avatar. I am having difficulty coding to check for the press of these keys. In Pascal it was easy enough to use "readkey" and code, for example, for #80 for the down keypress. However, I am stumped how to implement the same functionality in Java, though I think I understand the use of System.in and BufferedInputStream.

谁能帮帮我?非常感谢您的想法或提示.

Could anyone help me out? Your thoughts or hints are much appreciated.

推荐答案

Java 中的控制台支持问题众所周知,我不确定这是否可行.

The Console support issue in Java is well known, I am not sure that this is doable.

这在 System.in 最初是不可能的,因为它曾经是基于行的.

This was not initially possible with System.in since it used to work line-based.

Sun 最终添加了一个 java.io.Console 类.

Sun eventually added a java.io.Console class.

这里是它的 JavaDocs:http://java.sun.com/javase/6/docs/api/java/io/Console.html

Here are its JavaDocs: http://java.sun.com/javase/6/docs/api/java/io/Console.html

一旦你得到控制台(我认为是从 System.console 获得的),你就可以得到一个阅读器,也许可以从中读取字符,但我不确定它是否包含键.

Once you get the console (I think from System.console), you can get a reader and perhaps read characters from it, but I'm not sure if it includes keys.

一般来说,如果你想使用键盘,你应该使用 Swing 或 AWT,这很愚蠢.

Generally, you're supposed to use Swing or AWT if you want access to the keyboard, which is silly.

截至 2007 年,有一个关于它的功能请求:这里

As of 2007, there was a feature request about it: here

相关文章