Java 检测控制台中的按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27381021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:15:54  来源:igfitidea点击:

Detect a key press in console

java

提问by LightMikeE

I want to execute a certain function when a user presses a key. This will be run in the console, and the code is in Java. How do I do this? I have almost zero knowledge of key presses/keydowns, so I could really use an explanation as well.

我想在用户按下某个键时执行某个功能。这将在控制台中运行,代码使用 Java。我该怎么做呢?我对按键/按键的知识几乎为零,因此我也可以真正使用解释。

采纳答案by Gren

If you want to play with the console, you can start with this:

如果你想玩控制台,你可以从这个开始:

import java.util.Scanner;

public class ScannerTest {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        boolean exit = false;
        while (!exit) {
            System.out.println("Enter command (quit to exit):");
            String input = keyboard.nextLine();
            if(input != null) {
                System.out.println("Your input is : " + input);
                if ("quit".equals(input)) {
                    System.out.println("Exit programm");
                    exit = true;
                } else if ("x".equals(input)) {
                    //Do something
                }
            }
        }
        keyboard.close();
    }
}

Simply run ScannerTest and type any text, followed by

只需运行 ScannerTest 并输入任何文本,然后输入

回答by SalGnt

You can't detect an event in the command line environment. You should provide a GUI, and then you can use the KeyListenerclass to detect a keyboard event.

您无法在命令行环境中检测到事件。您应该提供一个 GUI,然后您可以使用KeyListener该类来检测键盘事件。

Alternatively you can read commands from standard input and then execute a proper function.

或者,您可以从标准输入读取命令,然后执行适当的功能。