Home >Java >javaTutorial >How to Add Color to Console Output Using System.out.println()?

How to Add Color to Console Output Using System.out.println()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 22:53:19532browse

How to Add Color to Console Output Using System.out.println()?

How to Inject Color into Console Output with System.out.println()

Question:

How do I effortlessly infuse color into my console output to visually differentiate data?

Answer:

Embracing the power of ANSI escape codes, you can unleash a vibrant spectrum of colors in your console output. This technique, predominantly supported by Unix shell prompts, provides a convenient way to enhance data presentation. If you wish to enchant your terminals with this chromatic magic, simply follow these steps:

  1. Define constants representing your desired color palette, as showcased 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";
  1. To illustrate, let's paint our console a vibrant shade of red:
System.out.println(ANSI_RED + "This text dances in fiery crimson!" + ANSI_RESET);
  1. Should you desire to venture beyond text color, you can also alter the background hue:
public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";

System.out.println(ANSI_GREEN_BACKGROUND + "Emerald hues adorn this text's canvas!" + ANSI_RESET);
  1. For added versatility, consider exploring the Jansi library. It seamlessly integrates with Windows using JNI, opening up a world of colorful possibilities.
  2. Remember that these vibrant transformations may only grace terminals that acknowledge ANSI escape codes. If your Windows Command Prompt stubbornly resists, Cygwin may offer a compatible alternative.

With this newfound control over console colors, you can effortlessly transform data into a visual masterpiece, adding depth and clarity to your programs' output.

The above is the detailed content of How to Add Color to Console Output Using System.out.println()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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