简体   繁体   中英

How to change the colors of text and background for cmd in Java?

I have been doing Java for a while now and I have never seen a tutorial on how to make cmd change colors of text and background. In C++ you can just use SetConsoleTextAttribute(); and it will change the color of bg and text. Is there a class you import in Java to allow you to do that, or is there a third party API that you have to download? Thanks in advance.

Try ANSI escape code http://en.wikipedia.org/wiki/ANSI_escape_code

System.out.println("\033[6mHello world");

may not work on your console though...

Download jansi-1.4.jar 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 Sample
{
  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();
  }
}

If this is for use with windows(cmd) specifically then:

new ProcessBuilder("cmd", "/c", "color XX").inheritIO().start().waitFor();

should give you the result you are after.

Where XX is the color code corresponding to the background and text color that you want to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM