Hello. Does anyone know how I would set the colour of a string before printing it so that the string changes colour?
Thanks.
Hello. Does anyone know how I would set the colour of a string before printing it so that the string changes colour?
Thanks.
Hi you can use g.setColor(). Assuming you use Graphics g in an AWT context.
Please refer to the documentation for additional information.
Strings don't encapsulate color information. Are you thinking of setting the color in a console or in the GUI?
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 );
}
}
}
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:
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.
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
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.
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)