Execute a KeyListener in a Java console app
KeyListener
is not meant for console apps. What you could do is read one character at a time using System.in.read()
Another method to have a sort of console KeyListener
is by using the JNI. You can install a global keyboard hook and listen for keypress. The JNativeHook library will be useful if you want to do it in this way. You do not need to use Swing or other GUI classes.
Is there a way to use KeyListener in Java to be used in command line application?
Take a look at this thread, there are some solutions here: How to read a single char from the console in Java (as the user types it)?
To accomplish this you need to set your console into raw mode. Apparently there is no built-in way to do so with Java, but there are some libraries you could use to get there, like jCurses or jLine3.
Java - key event listener
As far as I understand you want to enable non blocking IO from console application. This cannot be done with JDK only, but fortunately there are several 3rd party libraries that enable this functionality.
Take a look on the following discussions:
What's a good Java, curses-like, library for terminal applications?
How to determine if anything has been entered into the console window?
how can I detect arrow keys in java console not in GUI?
Listening to system mouse clicks from Java
Detect a key press in console
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'
Java easiest keylistener
When you setup the JFrame, add a KeyListener like this:
JFrame jf = new JFrame("title");
jf.addKeyListener(new MyKeyListener());
jf.setVisible(false);
(The jf.setVisible(false);
stops the program window from appearing (only command line)
Then create a new class called MyKeyListener
that extends KeyAdapter
.
class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()== KeyEvent.VK_Q)
System.out.println("Key Q pressed!");
}
}
Now let me explain things a bit.
First, when you create a JFrame, it has no default KeyListener
attached. Therefore, we have to create a class MyKeyListener
to do that.
Secondly, we extended KeyAdapter instead of implementing KeyListener because there are a lot more methods than what you need in there. You only need to override the keypressed()
method when you extends KeyAdapter but you have to implement all (I think it's 3) the other methods that you don't need for your purposes.
Lastly, if you want to do other methods like keyreleased()
, just add it in to the MyKeylistener
class and it will work.
Hope this helps!
EDIT: Per OP's request, it should be like this:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (line.equalsIgnoreCase("q") == false) {
line = in.read();
System.out.println("Q is pressed!");
}
in.close();
How to listen to keyboard events in a console application
This is slightly more complicated than it looks.
Maybe you should have a look at the jline project that handles everything for you.
Related Topics
Differencebetween Reader and Inputstream
How to Clear Permgen Space Error in Tomcat
What Are the Date Formats Available in Simpledateformat Class
How to Use This Boolean in an If Statement
How to Read Excel Cell Having Date with Apache Poi
What Do Curly Braces in Java Mean by Themselves
How to Use Argumentcaptor for Stubbing
Converting a String to Color in Java
How to Create a Delay in Swing
Rejectedexecutionexception Inside Single Executor Service
Java: Infinite Loop Using Scanner In.Hasnextint()
How to Convert a Java Object to Xml with Open Source APIs
Using Variables Outside of an If-Statement
Ordering of Elements in Java Hashset
What's the Meaning of System.Out.Println in Java
Spark Spark-Submit --Jars Arguments Wants Comma List, How to Declare a Directory of Jars
Get Key Press Without Pressing Enter in Console
How to Specify the Default Jvm Arguments for Programs I Run from Eclipse