📜  如何在Java控制台中打印彩色文本?

📅  最后修改于: 2021-10-28 02:54:07             🧑  作者: Mango

请记住,在Java Programming 中,输出屏幕的背景颜色和文本颜色默认为黑色或白色。如果我们想在输出屏幕上突出显示某些文本,那么我们可以使用 ANSI 颜色代码并突出显示特定文本。可以参考 ANSI 转义码以了解更多信息。

句法:

System.out.println(ANSI_COLORNAME + "This text is colored" + ANSI_RESET);

从上面的语法可以看出包含此语法包含 3 个部分:

  • ANSI_COLORNAME 中,我们必须写出我们给出特定 ANSI 代码的名称。例如 public static final String ANSI_BLACK = “\u001B[30m”;
  • 第二部分是编写我们要以该颜色打印的文本。
  • ANSI_RESET代码关闭到目前为止设置的所有 ANSI 属性,这应该将控制台返回到其默认值。

以下是ANSI颜色代码表:

Color Name Color code Background Color Background Color code
BLACK \u001B[30m BLACK_BACKGROUND \u001B[40m
RED \u001B[31m RED_BACKGROUND \u001B[41m
GREEN \u001B[32m GREEN_BACKGROUND \u001B[42m
YELLOW \u001B[33m YELLOW_BACKGROUND \u001B[43m
BLUE \u001B[34m BLUE_BACKGROUND \u001B[44m
PURPLE \u001B[35m PURPLE_BACKGROUND \u001B[45m
CYAN \u001B[36m CYAN_BACKGROUND \u001B[46m
WHITE \u001B[37m WHITE_BACKGROUND \u001B[47m

插图: Java的文本着色:

示例 1:

Java
// Java Program to Print Colored Text in Console
  
// Importing input output classes
import java.io.*;
  
// Main class
public class GFG {
  
    // Declaring ANSI_RESET so that we can reset the color
    public static final String ANSI_RESET = "\u001B[0m";
  
    // Declaring the color
    // Custom declaration
    public static final String ANSI_YELLOW = "\u001B[33m";
  
    // Main driver method
    public static void main(String[] args)
    {
        // Printing the text on console prior adding
        // the desired color
        System.out.println(ANSI_YELLOW
                           + "This text is yellow"
                           + ANSI_RESET);
    }
}


Java
// Java Program to Print Colored Text in Console
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Declaring ANSI_RESET so that we can reset the color
    public static final String ANSI_RESET = "\u001B[0m";
    // Declaring the background color
    public static final String ANSI_RED_BACKGROUND
        = "\u001B[41m";
  
    // Main driver method
    public static void main(String[] args)
    {
        // Now add the particular background color
        System.out.println(ANSI_RED_BACKGROUND
                           + "The background color is red"
                           + ANSI_RESET);
    }
}


输出:

示例 2:

Java

// Java Program to Print Colored Text in Console
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Declaring ANSI_RESET so that we can reset the color
    public static final String ANSI_RESET = "\u001B[0m";
    // Declaring the background color
    public static final String ANSI_RED_BACKGROUND
        = "\u001B[41m";
  
    // Main driver method
    public static void main(String[] args)
    {
        // Now add the particular background color
        System.out.println(ANSI_RED_BACKGROUND
                           + "The background color is red"
                           + ANSI_RESET);
    }
}

输出: