如何使用System.out.println在控制台中打印颜色? [英] How to print color in console using System.out.println?
问题描述
如何在控制台中打印颜色?我希望在处理器发送数据时显示颜色数据,并在接收数据时以不同颜色显示数据。
How can I print color in console? I want to show data in colors when the processor sends data and in different colors when it receives data.
推荐答案
如果您的终端支持它,您可以使用 ANSI转义码在输出中使用颜色。它通常适用于Unix shell提示;但是,它不适用于Windows命令提示符(虽然它确实适用于Cygwin)。例如,您可以为颜色定义这些常量:
If your terminal supports it, you can use ANSI escape codes to use color in your output. It generally works for Unix shell prompts; however, it doesn't work for Windows Command Prompt (Although, it does work for Cygwin). For example, you could define constants like these for the colors:
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";
然后,您可以根据需要参考这些。
Then, you could reference those as necessary.
例如,使用上面的常量,您可以在支持的终端上输出以下红色文本:
For example, using the above constants, you could make the following red text output on supported terminals:
System.out.println(ANSI_RED + "This text is red!" + ANSI_RESET);
更新:您可能想要查看 Jansi 库。它提供API并支持使用JNI的Windows。我还没有尝试过;然而,它看起来很有希望。
Update: You might want to check out the Jansi library. It provides an API and has support for Windows using JNI. I haven't tried it yet; however, it looks promising.
更新2:此外,如果您希望将文本的背景颜色更改为其他颜色,也可以尝试以下方法:
Update 2: Also, if you wish to change the background color of the text to a different color, you could try the following as well:
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";
public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";
例如:
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);
这篇关于如何使用System.out.println在控制台中打印颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!