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.
Asked
Active
Viewed 3.6k times
20
-
10So, a reason for the down-vote would be nice. One could improve with some constructive criticism, with constructive being the key word here. – LightMikeE Dec 09 '14 at 14:41
-
As a note, frameworks like `JNativeHook` can provide global hooks to the key events by going through the Windows API. – Zabuzard Sep 16 '20 at 08:15
2 Answers
9
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.

SalGnt
- 127
- 1
- 5
-
5The requirement is to do so in a command line, and I've been told that it can be done in C++. So, why not Java? – LightMikeE Dec 09 '14 at 14:34
-
maybe because in C++ you have access to OS functions, while in Java you need a java ui to capture key press ? Here is a related thread : https://stackoverflow.com/a/4609067/4802862 – georges abitbol Feb 14 '18 at 07:43
-
2Technically, you can add a global key listener hook using the windows api and listen for keypresses like that. There are frameworks like JNativeHook for that. – Zabuzard Sep 16 '20 at 08:14
-2
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'

Gren
- 1,850
- 1
- 11
- 16
-
-
-
26In my knowledge `keyboard.nextLine()` does not detect keypress. It return the line after user has pressed Enter. – Daniel Cheung Dec 04 '16 at 09:49
-
2
-
2This does not answer the OP's question tbh. This just reads an entire line from standard input. This does not handle key events like keypress or keydown/keyup. – Andria Aug 13 '21 at 00:50