简体   繁体   中英

change color of a string in java

how to change the color of a string in console depending on it's value. Eg:if 's' is a string declared in a class .

i have a method that returns ( success or failure) using if else. now i want to assign the return value of method to 's' and change the color in which it is displayed in console. ie,if 'success'.print in green color etc;

A string itself doesn't have any formatting information. How you display a string in a particular way will depend on the output context - for example, in a console you may be able to use ANSI escape sequences (if your console supports them); in HTML you'd use styling (or similar); in a Swing UI you'd potentially change the foreground colour of the control.

So if you know you're going to use a terminal/console, try the ANSI escape codes I linked to - but be aware that they won't work universally.

The standard Java text console is cross-platform, so it doesn't support colour natively. You could, depending on your platform, use different escape codes etc. to get the result required, but all fo this quite error-prone and involves a lot of extra work.

Here's a suggestion:

Give the Jansi library (http://jansi.fusesource.org/) a whirl.

You can read up more on ANSI codes here http://www.ioncannon.net/ruby/101/fun-with-ansi-escape-codes/

With the Jansi library, you should be able to colour your text as you wish, for example :

    AnsiConsole.systemInstall();
    AnsiConsole.out.println("\033[32mHowdy");

The code above prints the Howdy in green, in the console, although this does not work well from within the IDE. However, when I run it on my machine from the command-line, it works as expected.

Best of luck!

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