0

i have two threads: one of them (server) is printing something to the console and the other (user) one is taking input from console. The problem occurs if the first thread prints something while user is typing into console. it looks like for example

command from usermessage from server 

or if the user hasn't typed the command fully

commmessage from server

and it messes up the command from the user

is there a way to make it look like

message from server
command from user

or

message from server
comm

so to print one line above the currently typed text in the console and maintain the user input. i still want the first thread to print while the user is typing so locking this thread untill user enters the command isn't an option

  • Which OS are you using? Your problem comes down to being able to position the cursor and that varies with OS. E.g. https://stackoverflow.com/questions/15051688/is-it-possible-to-rewrite-previous-line-in-console – jtalics Sep 27 '22 at 15:22
  • windows but working with intellij idea console – Kuba Samulski Sep 27 '22 at 15:29
  • This might help: https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#simple-cursor-positioning – jtalics Sep 27 '22 at 17:43
  • Another approach is to use an ncurses library such as https://github.com/wmcbrine/PDCurses It takes over the console and draws a "GUI" with ascii characters. In any of these cases, you will want to keep everything in a memory buffer and whenever there is an event such as key press or incoming data to be displayed, you will reposition the cursor to home and redraw the buffer. – jtalics Sep 27 '22 at 17:50

1 Answers1

0

[I want] to print one line above the currently typed text in the console and maintain the user input.

There are no easy answers here unfortunately. The user input being entered is actually being echoed by the terminal and not by the Java program. You have no control over the input and can't reprint it once the standard output is displayed.

The only way to do this otherwise is to turn off terminal echoing and control the user keystrokes in your program, but that makes it a lot more complicated. See: How to disable console echoing

You could also use some sort of Java dialog box and then pop the standard out message in another dialog or let it go to standard out.

i still want the first thread to print while the user is typing so locking this thread until user enters the command isn't an option

Yeah I fear that locking out the standard output messages is only way for you to do this unless you want to use a different mechanism to get your user input.

Gray
  • 115,027
  • 24
  • 293
  • 354