Short version of my question:
__________________________________________
How can I detect a keypress in Java without using a GUI?
Long Version:
__________________________________________
I am writing a program that users System.out and System.in for its input and output. As you are no doubt familiar, if you are in the middle of typing something and the program sends something to System.out, it will just put it right on top of where you were typing and move you to the next line and it all just looks like a mess.
Say you are typing "this is a line" and after you type the second "i" but before you type the "n", the program returns "OUTPUT\n". Your screen looks like this:
this is a liOUTPUT
ne
To make things a little cleaner, you can put a "\r" at the beginning of each line of output so that output will always be placed at the start of the line... but then you still have to just remember what you typed before that. Here's the same situation, only the program outputs "\rOUTPUT\n":
OUTPUT
ne
I am trying to clean this up a bit and make my program more user friendly. I want to set it up so that if you are in the middle of typing something and the program returns output, everything you have typed so far gets moved down one line and the output appears on the line you were just typing on.
So the same example would look like this:
OUTPUT
this is a line
I hope that description makes sense.
To do that, I have developed a (very overly complicated) method to implement this... but it relies on me being able to do one very important thing that I have not yet figured out how to do: I need to be notified of each keypress right after it happens rather than waiting for the user to press enter and send an entire line of text.
I have tried wrapping System.in to a BufferedInputStream with a size of 1... no effect.
I have tried using an invisible JFrame to implement KeyListener, but apparently elements can only get KeyEvents if they are both visible and in focus.
My last resort is to try to set the console into cbreak mode... which means each character becomes available as soon as it is typed. But I can't figure out how to do that under Windows. The Java program will start from a batch file, so I can issue any Windows command line commands that I need to before running the program... I could also run a .exe file or something like that. But so far I have not found anything that will allow me to put the Windows terminal into single character buffer mode instead of line buffer mode.
These are just some ideas of the things I have tried in case they give anyone an idea. All I want to do is detect keypresses in Java from the console without launching a visible GUI.
Can anyone think of a way to do this?