How to print color in console using System.out.println?
To create colorful console output in Java, you can utilize the power of ANSI escape codes:
This changes the text color to red using \u001B[31m
, then it resets the color with \u001B[0m
. Usually, terminals supporting ANSI colors will display this correctly, however, it's beneficial to verify compatibility.
A spectrum of opportunity with ANSI codes
Dynamically change your console's background and text color by defining color constants. This facilitates an easy switch between colors in your code, increasing its readability and maintainability.
Colors for friendly data differentiation
Use different ANSI colors for different data types to aid in the identification of errors, informational log, critical warning, or verbose log. With Windows environments, boost the support of ANSI codes using the Jansi library.
Mastering external libraries and utilities
COLORS powered by JColor
The JColor library facilitates manipulating console colors with its easy-to-use 8 and 24-bit color formats, allowing your console outputs to shine.
Conquer complexity with ConsoleColors class
A custom ConsoleColors class simplifies color management by providing public static fields for each common color.
Colorful enums for dynamic control
An enum "Color" with pre-defined escape sequences promotes dynamic color output while maintaining readability.
Caution: Older Windows consoles and ANSI
Older Windows consoles may struggle with ANSI escape codes. Check your audience's terminal to ensure a seamless user experience.
Verifying ANSI compatibility
Before painting with all the colors of the wind, ensure the terminal supports ANSI escape codes.
Friendly fallback
In unsupported terminals, printing the message without ANSI codes maintains your application's professional demeanor and coherence.
Never forget to hit Reset
Ensure to reset the console color after each output, to protect the succeeding text from unwanted coloring.
Was this article helpful?