-1

I want to determine cursor position in a Java console application.

This can be achieved by the following ANSI code sequence:

ESC[6n

If I send that ANSI escape command I get the answer, but I can not retrieve it in Java. This is what I have tried:

public class ConsoleTest {

    public static final String ANSI_GET_CURSOR_POSITION = "\u001B[6n";


    public ConsoleTest() {

        System.out.println(ANSI_GET_CURSOR_POSITION);

        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));   
        String str = null;

        do {   

            try {
                str = obj.readLine();   
                System.out.println(str);
            } catch (IOException ex) {
                Logger.getLogger(ConsoleTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        } while(!str.equals("stop"));           


    }

}

This is what I get, even pressing ENTER does nothing:

% java -jar ConsoleTest.jar

^[[24;1R

stop               
stop

So apparently, console answers with the code but I can not read it in the Java application.

M.E.
  • 4,955
  • 4
  • 49
  • 128
  • Does this help? [Java gotoxy(x,y) for console applications](https://stackoverflow.com/questions/1001335/java-gotoxyx-y-for-console-applications) – Abra May 26 '20 at 17:53
  • Your observation is wrong; pressing ENTER _does_ cause Java to read the response, but your code then _outputs_ that same response (`System.out.println(str)`) which does nothing. However, the response is not a line, so if you don't want to wait for ENTER, don't use `readLine`. – dave_thompson_085 May 26 '20 at 18:19

1 Answers1

0

Here is a similar question where you can find how to read the cursor position with simple Java program: How to read the cursor position given by the terminal (ANSI Device Status Report) in JAVA

Sergiy Kozachenko
  • 1,399
  • 11
  • 31