如何设置字符串的颜色 [英] How to set a string's color
问题描述
有谁知道如何设置将使用 System.out
打印的字符串的颜色?
这是我当前的代码有:
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.");
推荐答案
控制台
有关序列的完整集合,请参阅 ANSI转义维基百科页面,其中包括
Console
See the Wikipedia page on ANSI escapes for the full collection of sequences, including the colors.
但是对于Java中的一个简单示例(以红色打印)(如标记为Java):
But for one simple example (Printing in red) in Java (as you tagged this as Java) do:
System.out.println("\u001B31;1mhello world!");
3表示更改颜色,前1表示红色(绿色为2)
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最简单的方法是使用html:
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>");
有关此类事物的更多详细信息,请参阅 Swing教程。也可以通过在JTextPane中使用样式。 这里是一个有用的示例的代码,轻松地做到这一点一个JTextPane(从有用的注释添加)。
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是一个单色文本组件,如此处所述。它只能以一种颜色显示。你可以像这样设置整个JTextArea的颜色:
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)
这篇关于如何设置字符串的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!