I am writing an application that requires me to read a key from console without having to wait for the user to hit enter. I have read that JCurses library could help.
I tried using Toolkit.readCharacter()
like this:
InputChar c = Toolkit.readCharacter();
system.out.println(c.getCharacter());
But the problem was that the readCharacter()
method does not end execution no matter how many characters you input. Even if you press enter, it still seems that it is waiting for you to enter a character.
I really appreciate any help using JCurses, or any other way would do.
Java Curses has a couple of specific keystroke recognition methods, but tying yourself down to an external library for a single function may not be the best solution.
What you are after could be achieved by creating a terminal-style Swing application, and using a
KeyListener
to detect keystroke events. However, MadProgrammer notes in How to make esc stop a method that such a solution may have "focus issues".So if you want to trace specific keystrokes, or want to affect program behaviour based on different user inputs, I would recommend using key bindings which are implemented as part of Swing.
e.g.
Where component is any
JComponent
object (assumably a terminal display), andyourAction
is any Swing action. Using the paramaterised form ofgetInputMap()
as shown here is preferable for a "console" application, as the user will necessarily making keystrokes within the top level window, and therefore component focus is irrelevant.