如何使用 System.out.println 在控制台中打印颜色? [英] How to print color in console using System.out.println?

查看:36
本文介绍了如何使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆