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. i.e,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!
精彩评论