Scott Forsythe
Scott Forsythe

Reputation: 370

Setting color of user input text after printing an ANSI-colored message?

I am running a console application in Netbeans that prompts a user input, validates the input, and prints an error message if the input failed validation and re-prompts. The error message I have set up to print in red text per this answer. It works perfectly, save one issue.

After the program asks for a second input given that the first input was invalid, user inputs following that error message are the same color as the error message.

For example, the user has entered an invalid input. They enter their input again after the error message. It should print in the default text color (black in my version), but it prints as red text instead.

Is there a way in which I am supposed to close out the application of the ANSI color code on my text? An end tag of sorts?

Code:

public static void main(String[] args) 
{

    //Initialize keyboard input
    Scanner keyboard = new Scanner(System.in);

    //Print prompt to screen
    System.out.println("User input prompt goes here: ");

    //Store user input
    String inputGot = keyboard.nextLine();

    //Print a dummy error message
    System.out.println("\u001B[31m" + "This is an error of some sort.  "
            + "Please re-enter input: ");

    //Rerun input prompt (this would be looped in the real program)
    System.out.println("User input prompt goes here: ");

    //Store user input
    inputGot = keyboard.nextLine();
}

Upvotes: 1

Views: 1564

Answers (1)

BeUndead
BeUndead

Reputation: 3618

Wherever you want the red text to stop, you need to insert the ANSI escape sequence to set all ANSI attributes off: "\u001b[0m".

See this for other things you might want/need. https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes

Upvotes: 2

Related Questions