Home > Java > javaTutorial > How Can I Add Color to My Console Output Using ANSI Escape Codes?

How Can I Add Color to My Console Output Using ANSI Escape Codes?

Susan Sarandon
Release: 2024-12-17 08:40:25
Original
971 people have browsed it

How Can I Add Color to My Console Output Using ANSI Escape Codes?

Colorized Console Output with ANSI Escape Codes

Console output can be enhanced with colors to improve readability and highlight important data. ANSI escape codes provide a straightforward approach to achieve this if your terminal supports them.

Defining Color Constants

Create constants representing different colors, as demonstrated below:

public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
Copy after login

Usage

Use the color constants to add color to your text output, as exemplified by the following code:

System.out.println(ANSI_RED + "This text is red!" + ANSI_RESET);
Copy after login

This will print the message "This text is red!" in red on supported terminals.

Background Coloring

In addition to text color, you can also modify the background color using similar constants:

public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
...
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";
Copy after login

Example Output

Here's an example of using both text and background colors:

System.out.println(ANSI_GREEN_BACKGROUND + "This text has a green background but default text!" + ANSI_RESET);
System.out.println(ANSI_RED + "This text has red text but a default background!" + ANSI_RESET);
System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET);
Copy after login

This will produce output with text in different colors and backgrounds, enhancing the overall readability of your console output.

The above is the detailed content of How Can I Add Color to My Console Output Using ANSI Escape Codes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template