0

I want to execute some codes at the time when user presses the keyboard.

I tried the following code:

  public static String content = "";
  public static boolean running = true;

  public static void startListen() {
    running = true;
    new Thread(() -> {
      while (running) {
        try {
          byte b[] = new byte[1];
          System.in.read(b);
          char c = (char) b[0];
          System.out.println("hit :" + c);//Here to output which key is pressed
          //run some code
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }).start();
  }
  //Omit other code for controlling the thread

But I find that unless the user presses enter, the codes will not work.

I tried to disable buffer in System.in but nothing change.

0 Answers0