Color is one of the most powerful tools for improving the usability of terminal applications. By applying different colors to text, developers can highlight important information, distinguish between message types, and create visually structured interfaces.
Terminal colors are implemented using ANSI escape codes, which instruct the terminal to modify how text is displayed. Most modern terminal emulators support these codes, making it possible to create colorful and readable command-line applications.
For Java programs, libraries such as Jansi help ensure ANSI color support works consistently across different operating systems.
1. Standard Colors
The original ANSI standard defined eight basic colors that terminals can display. These are known as the standard foreground colors.
|
Code |
Color |
|
30 |
Black |
|
31 |
Red |
|
32 |
Green |
|
33 |
Yellow |
|
34 |
Blue |
|
35 |
Magenta |
|
36 |
Cyan |
|
37 |
White |
For example, the code ESC[31m sets the foreground color to red. In Java code, the escape sequence usually appears as \u001B[31m.
System.out.println("\u001B[31mError occurred\u001B[0m");
Here:
· 31 → red text
· 0 → reset formatting back to default
ColoredLogViewer.java
package com.sample.app.chapter2; import org.fusesource.jansi.AnsiConsole; public class ColoredLogViewer { public static void main(String[] args) throws Exception { AnsiConsole.systemInstall(); for (int i = 1; i <= 10; i++) { printInfo("Starting task " + i); Thread.sleep(500); printDebug("Loading configuration..."); Thread.sleep(500); printWarning("Cache is nearing capacity"); Thread.sleep(500); if (i % 3 == 0) { printError("Connection timeout while accessing API"); } else { printSuccess("Task completed successfully"); } Thread.sleep(1000); System.out.println(); } AnsiConsole.systemUninstall(); } private static void printInfo(String msg) { System.out.println("\u001B[34m[INFO] " + msg + "\u001B[0m"); } private static void printDebug(String msg) { System.out.println("\u001B[36m[DEBUG] " + msg + "\u001B[0m"); } private static void printWarning(String msg) { System.out.println("\u001B[33m[WARNING] " + msg + "\u001B[0m"); } private static void printError(String msg) { System.out.println("\u001B[31m[ERROR] " + msg + "\u001B[0m"); } private static void printSuccess(String msg) { System.out.println("\u001B[32m[SUCCESS] " + msg + "\u001B[0m"); } }
2. Background Colors
In addition to foreground colors, ANSI escape codes can change the background color behind the text.
Background colors use codes 40–47.
|
Code |
Background Color |
|
40 |
Black |
|
41 |
Red |
|
42 |
Green |
|
43 |
Yellow |
|
44 |
Blue |
|
45 |
Magenta |
|
46 |
Cyan |
|
47 |
White |
For example, the code ESC[44m sets the background color to blue.
Example:
System.out.println("\u001B[37;44mInfo Message\u001B[0m");
Here:
· 37 → white text
· 44 → blue background
SystemStatusBoard.java
package com.sample.app.chapter2; import org.fusesource.jansi.AnsiConsole; public class SystemStatusBoard { public static void main(String[] args) { AnsiConsole.systemInstall(); System.out.println("\nSYSTEM HEALTH DASHBOARD\n"); printStatus("Auth Service", "RUNNING", "\u001B[37;42m"); // White text, Green background printStatus("Payment Service", "WARNING", "\u001B[30;43m"); // Black text, Yellow background printStatus("Inventory Service", "DOWN", "\u001B[37;41m"); // White text, Red background printStatus("Notification Service", "RUNNING", "\u001B[37;42m"); printStatus("Search Service", "MAINTENANCE", "\u001B[30;46m"); // Black text, Cyan background AnsiConsole.systemUninstall(); } private static void printStatus(String service, String status, String color) { System.out.println(service + " : " + color + " " + status + " \u001B[0m"); } }
Output
3. Bold and Bright Colors
Terminals also support text intensity modifiers, which can make colors appear brighter.
The most common modifier is: ESC[1m.
Examples
· ESC[1m : Enable bold or bright text.
· ESC[1;31m : Enable bold red text.
Example Java Code
System.out.println("\u001B[1;32mSuccess!\u001B[0m");
This technique is commonly used to highlight:
· success messages
· warnings
· errors
TestExecutionDemo.java
package com.sample.app.chapter2; import org.fusesource.jansi.AnsiConsole; public class TestExecutionDemo { public static void main(String[] args) throws Exception { AnsiConsole.systemInstall(); System.out.println("Running Application Tests...\n"); runTest("LoginServiceTest"); runTest("PaymentServiceTest"); runTest("InventoryServiceTest"); runTest("NotificationServiceTest"); System.out.println("\nTest execution finished."); AnsiConsole.systemUninstall(); } private static void runTest(String testName) throws Exception { System.out.println("Executing " + testName + "..."); Thread.sleep(500); double r = Math.random(); if (r < 0.6) { System.out.println("\u001B[1;32m✔ PASSED\u001B[0m"); // Bright Green } else if (r < 0.85) { System.out.println("\u001B[1;33m⚠ SKIPPED\u001B[0m"); // Bright Yellow } else { System.out.println("\u001B[1;31m✖ FAILED\u001B[0m"); // Bright Red } System.out.println(); } }
Sample Output looks like below.
4. 256-Color Support
While the original ANSI standard defined only 8 colors, modern terminals support 256 colors. This extended color system allows developers to select from a much larger palette.
The format used is: ESC[38;5;<color>m
Where
· 38 → foreground color
· 5 → indicates 256-color mode
· <color> → color index (0–255)
Example: ESC[38;5;208m
Meaning use color index 208, which is an orange-like shade.
Example Java Code
System.out.println("\u001B[38;5;208mCustom Orange Text\u001B[0m");
Similarly, background colors use: ESC[48;5;<color>m
Example: ESC[48;5;25m
Above statement sets the background to a deep blue tone.
The 256-color palette includes:
· standard colors
· grayscale tones
· extended RGB combinations
ColorPalette256Demo.java
package com.sample.app.chapter2; import org.fusesource.jansi.AnsiConsole; public class ColorPalette256Demo { public static void main(String[] args) { AnsiConsole.systemInstall(); System.out.println("ANSI 256 Color Palette\n"); for (int i = 0; i < 256; i++) { // Print colored block using background color System.out.print("\u001B[48;5;" + i + "m"); // Print color index System.out.printf(" %3d ", i); // Reset formatting System.out.print("\u001B[0m"); // Print 16 colors per row if ((i + 1) % 16 == 0) { System.out.println(); } } System.out.println("\n\nEach number represents the color index used in 256-color mode."); AnsiConsole.systemUninstall(); } }
Output
5. True Color Terminals
Modern terminal emulators support 24-bit color, also called true color. This allows programs to specify any RGB color, giving access to over 16 million colors.
The format used is: ESC[38;2;<r>;<g>;<b>m
Where:
· r → red value (0–255)
· g → green value (0–255)
· b → blue value (0–255)
Example: ESC[38;2;255;165;0m
Above statement produces orange text
Example Java code:
System.out.println("\u001B[38;2;255;165;0mTrue Color Text\u001B[0m");
True color support is common in modern terminal emulators such as iTerm2, Windows Terminal, and GNOME Terminal.
TrueColorGradientDemo.java
package com.sample.app.chapter2; import org.fusesource.jansi.AnsiConsole; public class TrueColorGradientDemo { public static void main(String[] args) { AnsiConsole.systemInstall(); System.out.println("True Color Gradient Demo\n"); // Generate gradient for (int i = 0; i < 80; i++) { int r = 255 - (i * 3); int g = 50; int b = i * 3; if (r < 0) r = 0; if (b > 255) b = 255; System.out.print("\u001B[48;2;" + r + ";" + g + ";" + b + "m "); } // Reset formatting System.out.print("\u001B[0m"); System.out.println("\n\nGradient generated using 24-bit RGB colors."); AnsiConsole.systemUninstall(); } }
Output
6. Color Themes
Many terminal applications use color themes to maintain visual consistency. Instead of assigning random colors throughout the code, applications define color roles such as:
· primary text
· error messages
· success messages
· warnings
· highlighted selections
Example Theme
· Error → Red
· Warning → Yellow
· Success → Green
· Info → Cyan
By organizing colors into themes, applications become easier to maintain and adapt to different terminal environments. Large CLI tools and dashboards often rely heavily on color themes to create a structured interface.
For example, system monitoring tools like btop use colors to distinguish between CPU usage, memory statistics, and system processes.
ThemedDashboard.java
package com.sample.app.chapter2; import org.fusesource.jansi.AnsiConsole; public class ThemedDashboard { // Theme definition static class Theme { static final String RESET = "\u001B[0m"; static final String PRIMARY = "\u001B[37m"; // White static final String INFO = "\u001B[36m"; // Cyan static final String SUCCESS = "\u001B[32m"; // Green static final String WARNING = "\u001B[33m"; // Yellow static final String ERROR = "\u001B[31m"; // Red static final String HIGHLIGHT = "\u001B[35m"; // Magenta } public static void main(String[] args) throws Exception { AnsiConsole.systemInstall(); System.out.println(Theme.PRIMARY + "=== APPLICATION STATUS DASHBOARD ===" + Theme.RESET); System.out.println(); printInfo("Server started on port 8080"); printSuccess("Database connection established"); printWarning("Cache memory usage is high"); printError("Payment service is unreachable"); printHighlight("New deployment available"); AnsiConsole.systemUninstall(); } private static void printInfo(String msg) { System.out.println(Theme.INFO + "[INFO] " + msg + Theme.RESET); } private static void printSuccess(String msg) { System.out.println(Theme.SUCCESS + "[SUCCESS] " + msg + Theme.RESET); } private static void printWarning(String msg) { System.out.println(Theme.WARNING + "[WARNING] " + msg + Theme.RESET); } private static void printError(String msg) { System.out.println(Theme.ERROR + "[ERROR] " + msg + Theme.RESET); } private static void printHighlight(String msg) { System.out.println(Theme.HIGHLIGHT + "[NOTICE] " + msg + Theme.RESET); } }
Output
7. Compatibility Issues
Although ANSI colors are widely supported, developers must be aware of compatibility differences across terminals and operating systems.
7.1 Windows Terminal Limitations (Older Versions)
Older versions of Windows Command Prompt historically had limited support for ANSI escape sequences. Modern versions, however, provide better compatibility, especially through tools like Windows Terminal.
Libraries such as Jansi help ensure ANSI color support works correctly across platforms.
7.2 Terminal Emulator Differences
Not all terminals support the same color capabilities:
|
Feature |
Support |
|
8 colors |
Nearly universal |
|
256 colors |
Supported by most modern terminals |
|
True color |
Supported by modern terminal emulators |
If a terminal does not support 256 or true colors, it may fall back to the closest available color.
7.3 Accessibility Considerations
Color choices should consider readability. For example:
· Avoid low contrast combinations
· Do not rely only on color to convey meaning
· Provide textual indicators for errors or warnings
This ensures terminal applications remain usable in different environments.
In summary, Terminal colors allow developers to improve the readability and usability of command-line applications. Using ANSI escape codes, programs can control foreground colors, background colors, text intensity, and advanced color palettes.
Modern terminals support multiple color levels:
· 8 standard ANSI colors
· 256 extended colors
· 24-bit true color
With thoughtful color usage and compatibility awareness, developers can create visually appealing terminal interfaces that remain functional across different platforms and terminal emulators.
Previous Next Home





No comments:
Post a Comment