Reputation: 271
How to detect keyboard input when user press anykey and then doSomething/Repeat Method, unless escape button without swing/awt ?
public static void isChecking(String x)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String anykey = null;
System.out.print("Press Anykey to Continue : ");
anykey = br.readLine();
//if pressanykey
main(null); //call main class
//if escape button
System.out.println("Good Bye ");
System.exit(1);
}
Thanks
MRizq
Upvotes: 4
Views: 9818
Reputation: 5792
There's no way to detect KeyPress in java with console I guess. Althought there's a way to do it natively, using JNI. You can get an example with source code from here
Regarding continuous input till you break, you can do it with simple while loop:
while((input = in.readLine()) != null){
System.out.println();
System.out.print("What you typed in: " + input);
}
Upvotes: 1
Reputation: 30855
try this way
public void keyPressed(KeyEvent e) {
while(!e.keyCode == Keyboard.ESCAPE) {
//do something
}
}
Upvotes: 0
Reputation: 1
Note, the escape button is not a character that will be passed in via System.in. Besides, you are using the readLine method so, if the user types "abc" and then enter, your anyKey variable will contain "abc".
Basically what you need to do is to listen on events on the keyboard. Check out this tutorial http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html.
Upvotes: 0
Reputation: 25158
How about a simple loop:
boolean escapeIsNotPressed = true;
while (escapeIsNotPressed) {
anyKey = br.readLine();
if (anyKey.equals(espaceCharacter)) {
escapeIsNotPressed = false;
} else {
main(null)
}
}
Not sure what is the String representation of the escape character. Try to show it using a System.out.println(anykey) and the introducing it in your code.
Upvotes: 0