0

Let's say I have a console app in Java that reads input from the user and then prints it back out (very basic)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        while(true) {
            Scanner scanner = new Scanner(System.in);
            String message = scanner.nextLine();
            System.out.println(message);
        }
    }
}

Is it possible to make the text the user enters when typing a different colour when compared to the text that is printed out with System.out.println?

For example if I ran that program in a console that defaults to white text on a black background the following would happen.

I would type "hello world" and it would show in red. When I press enter, it prints "hello world" in the default white.

As a bonus, is it possible to configure a background for the "hello world" when it is printed in red? This means that I can choose two contrasting colours in case a user has their console background at a default setting of red.

Thanks!

Shiv
  • 831
  • 1
  • 12
  • 29

2 Answers2

1

You can start a windows console by using this code:

Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe");
p.waitFor();

Use this code to start your Java-application and set the fontcolor / backgroundcolor of the console.

The /c- switch means that you give the console a command it should run. You can test this by clicking on (Windows) Start -> cmd /k color 2c ... this will start a console with some very ugly colors that you can change to suit your needs:

https://ss64.com/nt/color.html

Then use Sergei's methods to change the color of the Java-output to what you want.

Since I did not test this solution, I dont know if the colors will get lost after you've changed them with Sergei's methods! You have to try that.

Some side notes:

  • Why do you want to change the input-colors? This seems to be a lot of effort just for a fancy effect.
  • You might overwrite the preferences that a user has made on his console! For example I use a green font since I can read it better. Having a program change this color permanently(?) might upset a user.
  • This solution only works on windows. When a user runs it on a linux-based machine, this might fail. So you would have to implement a switch for the different OS like demonstrated here: https://stackoverflow.com/a/5738345/1368690
Community
  • 1
  • 1
hamena314
  • 2,969
  • 5
  • 30
  • 57
1

You need to do something like this:

import java.util.Scanner;

public class App {

    public static final String ANSI_RESET = "\u001B[0m";
    public static final String ANSI_RED = "\u001B[31m";
    public static void main(String[] args) throws Exception {


        System.out.println("Movie Name:" + ANSI_RED);
        Scanner read = new Scanner(System.in);
        String movieName = read.nextLine();
        System.out.println(ANSI_RESET +"\nMovie Genre:" + ANSI_RED);
        

    }
}
Usama Aziz
  • 169
  • 1
  • 10