Detect a key press in console

后端 未结 2 674
迷失自我
迷失自我 2020-12-03 22:08

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 k

相关标签:
2条回答
  • 2020-12-03 22:45

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

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

    0 讨论(0)
  • 2020-12-03 22:55

    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 'enter'

    0 讨论(0)
提交回复
热议问题