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:27
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 );
    }
}
}
查看更多
我命由我不由天
3楼-- · 2020-05-20 08:30

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

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();
  }
}
查看更多
ゆ 、 Hurt°
4楼-- · 2020-05-20 08:31

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.

查看更多
登录 后发表回答