Java 如何设置字符串的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/565252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:17:49  来源:igfitidea点击:

How to set a string's color

javacolorssystem.out

提问by

Does anyone know how I would set the color of a string that will be printed using System.out?
This is the code I currently have:

有谁知道我将如何设置将使用打印的字符串的颜色System.out
这是我目前拥有的代码:

System.out.println("TEXT THAT NEEDS TO BE A DIFFERENT COLOR.");

回答by TomHastjarjanto

setColor(). Assuming you use Graphics g in an AWT context.

设置颜色()。假设您在 AWT 上下文中使用 Graphics g。

Please refer to the documentationfor additional information.

有关其他信息,请参阅文档

回答by Jim

Strings don't encapsulate color information. Are you thinking of setting the color in a console or in the GUI?

字符串不封装颜色信息。您是否考虑在控制台或 GUI 中设置颜色?

回答by jedierikb

public class colorString
{

public static void main( String[] args )
{
    new colorString();   

}

public colorString( )
{
    kFrame f = new kFrame();
    f.setSize( 400, 400 );
    f.setVisible( true );
}

private static class kFrame extends JFrame
{
    @Override
    public void paint(Graphics g) 
    {
        super.paint( g );
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor( new Color(255, 0, 0) );
        g2d.drawString("red red red red red", 100, 100 );
    }
}
}

回答by heeen

If you're printing to stdout, it depends on the terminal you're printing to. You can use ansi escape codes on xterms and other similar terminal emulators. Here's a bash code snippet that will print all 255 colors supported by xterm, putty and Konsole:

如果要打印到标准输出,则取决于要打印到的终端。您可以在 xterms 和其他类似的终端模拟器上使用 ansi 转义码。这是一个 bash 代码片段,它将打印 xterm、putty 和 Konsole 支持的所有 255 种颜色:

 for ((i=0;i<256;i++)); do echo -en "\e[38;5;"$i"m"$i" "; done

You can use these escape codes in any programming language. It's better to rely on a library that will decide which codes to use depending on architecture and the content of the TERM environment variable.

您可以在任何编程语言中使用这些转义码。最好依赖一个库,该库将根据体系结构和 TERM 环境变量的内容来决定使用哪些代码。

回答by Rolf

Google aparently has a library for this sort of thing: http://code.google.com/p/jlibs/wiki/AnsiColoring

谷歌显然有一个用于此类事情的库:http: //code.google.com/p/jlibs/wiki/AnsiColoring

There's also a Javaworld article on this which solves your problem: http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

还有一篇关于这个的 Javaworld 文章可以解决您的问题:http: //www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

回答by Nick Fortescue

Console

安慰

See the Wikipedia page on ANSI escapesfor the full collection of sequences, including the colors.

有关ANSI 转义的完整集合,包括颜色,请参阅维基百科页面

But for one simple example (Printing in red) in Java (as you tagged this as Java) do:

但是对于 Java 中的一个简单示例(以红色打印)(如您将其标记为 Java),请执行以下操作:

System.out.println("\u001B31;1mhello world!");

The 3 indicates change color, the first 1 indicates red (green would be 2) and the second 1 indicates do it in "bright" mode.

3 表示改变颜色,第一个 1 表示红色(绿色将是 2),第二个 1 表示在“明亮”模式下进行。

GUI

图形用户界面

However, if you want to print to a GUI the easiest way is to use html:

但是,如果要打印到 GUI,最简单的方法是使用 html:

JEditorPane pane = new new JEditorPane();
pane.setText("<html><font color=\"red\">hello world!</font></html>");

For more details on this sort of thing, see the Swing Tutorial. It is also possible by using styles in a JTextPane. Here is a helpful exampleof code to do this easily with a JTextPane (added from helpful comment).

有关此类事情的更多详细信息,请参阅Swing 教程。也可以通过在 JTextPane 中使用样式来实现。这是一个有用的代码示例,可以使用 JTextPane 轻松完成此操作(从有用的注释中添加)。

JTextArea is a single coloured Text component, as described here. It can only display in one color. You can set the color for the whole JTextArea like this:

JTextArea 是一个单一的彩色文本组件,如此处所述。它只能以一种颜色显示。您可以像这样设置整个 JTextArea 的颜色:

JTextArea area = new JTextArea("hello world");
area.setForeground(Color.red)

回答by dialex

I created an API called JCDP, former JPrinter, which stands for Java Colored Debug Printer. For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive. For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.

我创建了一个名为JCDP的 API ,以前是 JPrinter,它代表Java Colored Debug Printer。对于 Linux,它使用 WhiteFang 提到的 ANSI 转义码,但使用单词而不是更直观的代码将它们抽象出来。对于 Windows,它实际上包含 JAnsi 库,但在其上创建了一个抽象层,维护了为 Linux 创建的直观和简单的界面。

This library is licensed under the MIT Licenseso feel free to use it.

这个库是在MIT 许可证授权的,所以可以随意使用它。

Have a look at JCDP's github repository.

查看JCDP 的 github 存储库

回答by Christian

for linux (bash) following code works for me:

对于 linux (bash) 以下代码对我有用:

System.out.print("3[31mERROR  3[0m");

the \033[31m will switch the color to red and \033[0m will switch it back to normal.

\033[31m 会将颜色切换为红色,而 \033[0m 会将其切换回正常。

回答by Raman

Download jansi-1.4.jar and Set classpath and Try This code 100% working :

下载 jansi-1.4.jar 并设置类路径并尝试此代码 100% 工作:

import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;

public class SampleColour
{
  public static void main(String[] args)
  {
    AnsiConsole.systemInstall();

    System.out.println(ansi().fg(RED).a("Hello World").reset());
    System.out.println("My Name is Raman");

    AnsiConsole.systemUninstall();
  }
}