How to set a string's color [closed]

2020-05-20 07:44发布

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.println("TEXT THAT NEEDS TO BE A DIFFERENT COLOR.");

9条回答
混吃等死
2楼-- · 2020-05-20 08:07

Google aparently has a library for this sort of thing: 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

查看更多
不美不萌又怎样
3楼-- · 2020-05-20 08:09

Console

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

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

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.

GUI

However, if you want to print to a GUI the easiest way is to use 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 example of code to do this easily with a JTextPane (added from helpful comment).

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 area = new JTextArea("hello world");
area.setForeground(Color.red)
查看更多
该账号已被封号
4楼-- · 2020-05-20 08:13

for linux (bash) following code works for me:

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

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

查看更多
戒情不戒烟
5楼-- · 2020-05-20 08:14

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

查看更多
▲ chillily
6楼-- · 2020-05-20 08:16

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

Please refer to the documentation for additional information.

查看更多
在下西门庆
7楼-- · 2020-05-20 08:16

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.

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

Have a look at JCDP's github repository.

查看更多
登录 后发表回答