Reputation: 11
I'm currently writing a program and I have this problem where I want to move the console's cursor to a specific location on the screen. I quickly found out that this isn't possible in java so I wrote a C# script that would do this for me, but I only can run program in a separate process.
Is there a way to solve this?
Also I'm trying not to use any extra libraries like jline.
Here are some code snippets:
C#
using System;
namespace setCursor
{
public class program
{
static void Main(string[] args)
{
int x = Convert.ToInt16(args[0]);
int y = Convert.ToInt16(args[1]);
Console.SetCursorPosition(x ,y);
}
}
}
java
try
{
ProcessBuilder pb = new ProcessBuilder("setCursor", "0", "0");
Process p = pb.start();
p.waitFor();
for(int i = 0; i < 30; i++)
{
for(int j = 0; j < 120; j++)
{
Thread.sleep(1);
System.out.print(ContentOnTheScreen[i][j]);
}
}
}
catch (Exception e)
{
System.out.println(e);
}
Upvotes: 1
Views: 154
Reputation: 15196
Windows Terminal / console in recent version of Windows supports ANSI / VT codes so you could achieve movement of character position with System.out.print
if your terminal is compatible. You will be able to tell by running this:
public class SetCursor {
private static String CSI = "\u001b[";
private static String at(int row, int col) {
return CSI+row+";"+col+"H";
}
public static void main(String[] args) throws InterruptedException {
System.out.println("HELLO");
System.out.print(at(1,1) + "ABCD");
System.out.print(at(10,5) + "EFGH");
System.out.println("WORLD");
for (int i = 0; i <= 100; i++) {
System.out.print(at(30,20) + " Progress: "+i+"%");
Thread.sleep(100);
}
}
}
It will either print the different values around the screen (running from a Windows Terminal Command Prompt), or if VT codes not supported (such as when running via IDE) the output might look strange:
HELLO
[1;1HABCD[10;5HEFGHWORLD
...
Upvotes: 0