'Detect a key press in console

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.



Solution 1:[1]

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'

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2