Can anyone tell me how to print my strings on terminal with color in Java? If there is a library for that purpose please introduce it to me, I rather use one than do the job myself:)
Thanks in advance.
Can anyone tell me how to print my strings on terminal with color in Java? If there is a library for that purpose please introduce it to me, I rather use one than do the job myself:)
Thanks in advance.
Yes there is. I've implemented a library named JTerminal in Java to print custom outputs on terminal, Including print and println with your desired foreground and background colors. It supports 8-bit 256 colors(XTerm code).
It's an easy to use library. To print your string with color you want, You just need to make a static call to print
or println
method:
import io.github.shuoros.jterminal.JTerminal;
import io.github.shuoros.jterminal.ansi.Color;
public class Main {
public static void main(String[] args) {
// Prints "Hello World!" with orange foreground color
JTerminal.println("Hello World!", Color.ORANGE);
// Prints "Hello World!" with orange foreground and white background color
JTerminal.println("Hello World!", Color.ORANGE, Color.WHITE);
}
}
You can also colorize your string with different colors in different ranges by one line of code:
import java.util.List;
import io.github.shuoros.jterminal.JTerminal;
import io.github.shuoros.jterminal.ansi.Color;
import io.github.shuoros.jterminal.util.TextEntity;
public class Main {
public static void main(String[] args) {
// Prints ">JTerminal:~ 1.0.2" with the colors of its logo
JTerminal.println(">JTerminal:~ 1.0.2", List.of(//
new TextEntity(0, 1, Color.DARK_SEA_GREEN_7), //
new TextEntity(1, 10, Color.ORANGE), //
new TextEntity(10, 12, Color.DARK_SEA_GREEN_7), //
new TextEntity(12, 18, Color.WHITE)));
}
}
To add JTerminal to your maven or gradle project you can add its dependecy:
<!-- https://mvnrepository.com/artifact/io.github.shuoros/JTerminal -->
<dependency>
<groupId>io.github.shuoros</groupId>
<artifactId>JTerminal</artifactId>
<version>1.0.2</version>
</dependency>
// https://mvnrepository.com/artifact/io.github.shuoros/JTerminal
implementation group: 'io.github.shuoros', name: 'JTerminal', version: '1.0.2'
Head over to JTerminal github repository for some examples.