Jack
Jack

Reputation: 3057

Getting a Color from a String input, getField

Question: I would like the user to enter a color (Red, blue) and it to be converted to be used with Color

I have been looking at this

Getting a Color from a String input, I understand that it would be best to use the JColorChooser or something alike although I do not have that luxary. This is the accepted answer for it.

String text = "red";
Color color;
Field field = Class.forName("java.awt.Color").getField(text.toLowerCase()); // toLowerCase because the color fields are RED or red, not Red
color = (Color)field.get(null);

From this answer I see that it is really just concatinating ".RED" onto java.awt.Color,

Although I cannot seem to get this to work. Is their a better way to do this?

The reason I am doing this is in a simple program it will ask the user for a color ("red, blue, yellow etc")

I would then like to be able to save this color to a text file. Open the text file and load it, although I have this part allready, but I have not crossed the brigde of getting the color from the user. Sorry I'm still learning java so I apologise for any glaring mistakes.

Thanks.

Upvotes: 1

Views: 727

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

If I absolutely had to store my colors in a text file, I would use the int getRGB() method, translate the number to hex, and store the int as a String. Then parsing it back to an int and then a color would be trivial.

e.g.,

public static void writeOutMethod1(File file, List<Color> colorList) throws FileNotFoundException {
  PrintWriter pw = new PrintWriter(file);
  for (Color color : colorList) {
     pw.printf("%08x ", color.getRGB());
  }
  pw.close();
}

If I had to use Strings that are humanly understandable, I'd create my own Map to associate Strings with a color.

Upvotes: 1

Related Questions