1

I want to implement a feature where my console/CLI app stops running if it detects the "Control" key being pressed, in conjunction with some other key (ie. Control-B).

public class Example {

    public static void main(String[] args) {
        boolean hasBeenPressed = false;

        while(!hasBeenPressed) {
            // do something meaningful

            // If CONTROL-B has been pressed, stop the while loop
            if (controlBHasBeenPressed()) {
                 hasBeenPressed = true;
            }
        }
    }
}

I have been looking for a way to implement the controlBHasBeenPressed() function. Since there is no GUI for this app, I am reluctant to use the JavaFX libraries. So far, I have tried using a BufferedReader to detect this key event, but it doesn't work since CONTROL-B doesn't actually result in text that can be taken as input. How can I go about implementing this feature in Java?

  • The gist of what you want to do revolves around getting raw (character mode) access to `System.in`. This appears to be next to impossible without JNI or an ugly hack using `stty` (on Linux). The duplicate I marked explains why. – Jim Garrison Dec 10 '20 at 20:07

0 Answers0