Java: reading a key from the console without pressing the enter key

I want to interrupt the program when the user presses a special key. I try the code below, but its only work with the input key.

java.io.InputStreamReader reader = new java.io.InputStreamReader(System.in); boolean b = false; while(!b) { try{ if ( reader.ready()) { // read a character and process it System.out.println("key pressed"); b = true; } } catch (java.io.IOException ioex) { System.out.println("IO Exception"); } // edit, lets not hog any cpu time try { Thread.sleep(50); System.out.println("nop yet"); } catch (InterruptedException ex) { // can't do much about it can we? Ignoring System.out.println("Interrupted Exception"); } } 

Equivalent in C # (working):

  ConsoleKeyInfo k1 = new ConsoleKeyInfo('T', ConsoleKey.T, false, false, false); ConsoleKeyInfo k = Console.ReadKey(false); if (k== k1) { Environment.Exit(1); } 

Change 1:

I tried with threads and these lists, but not working either.

  public void keyTyped(KeyEvent e) public void keyPressed(KeyEvent e) public void keyReleased(KeyEvent e) 
+5
source share

All Articles