To change the text color in the console in Java, you can use ANSI escape codes. ANSI escape codes are special characters that can be used to change the formatting of text in the console, such as the text color, background color, and font style.
Here is an example of how you can use ANSI escape codes to change the text color in the console in Java:
public class Main { public static void main(String[] args) { // Use the ANSI escape code for red text System.out.println("\u001B[31mRed text\u001B[0m"); // Use the ANSI escape code for green text System.out.println("\u001B[32mGreen text\u001B[0m"); // Use the ANSI escape code for blue text System.out.println("\u001B[34mBlue text\u001B[0m"); } }
In this example, we use the ANSI escape codes for red, green, and blue text to print text in different colors to the console. The ANSI escape code consists of the escape character (\u001B
) followed by the color code in square brackets (e.g. [31m
for red text). To reset the text color to the default, we use the ANSI escape code for resetting the text attributes (\u001B[0m
).
Note that ANSI escape codes may not work on all platforms or console environments. If you need to change the text color in a more platform-independent way, you can use a library like Jansi (https://github.com/fusesource/jansi) or ANSIescape (https://github.com/aglover/java-ansi-escape-code) to handle the ANSI escape codes for you.