Java Color class question

Soldato
Joined
18 Oct 2002
Posts
9,044
Location
London
Here's the method I'm trying to use:
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Color.html#getColor(java.lang.String)

And I would have suspected at least one of these would have returned something, but they all return null!

System.out.println(Color.getColor("Color.RED"));
System.out.println(Color.getColor("Color.red"));
System.out.println(Color.getColor("red"));
System.out.println(Color.getColor("RED"));

How am I using this incorrectly?! It is a bit late, but I really don't understand it :confused:
 
Yeah it's imported fine. I get no errors. It's just doing what the method should do if it can't find the color, i.e. return null. But I don't know what sort of string I'm supposed to input to get a proper return value.

I even made a small test class just to check it wasn't anything else causing problems:


Code:
import java.awt.Color;

public class Test {
  public static void main(String[] args) {
    System.out.println(Color.getColor("Color.RED"));
    System.out.println(Color.getColor("Color.red"));
    System.out.println(Color.getColor("red"));
    System.out.println(Color.getColor("RED"));
    System.out.println(Color.getColor("java.awt.Color.RED"));
  }
}

There must be something obvious but I can't even see anything on google!
 
That's the point, it doesn't return anything!

If it returned a color we'd see the toString of the color and not NULL.
 
Thanks for that Visage!
It seems that I got the wrong interpretation of what this method does.

What I need is something like this:

Code:
String inputCommand = commandJTextField.getText();

if (Color.getColor(inputCommand) != null) {
	System.out.println("a valid color");
} else {
	System.out.println("an invalid color");
}

Where the user enters say... 'red' and I want to work out if it's a attribute of the Color class.
But I'm not sure that it's possible now. Any help would be great.

The only other way I can think is to have a massive if/else if structure where I define all the colors that the Color class supports.
But that's hardly ideal.
 
Last edited:
It's supposed to be just for the colours in the Color class, so things like purple or brown don't matter if they're entered.
I could use an array, but spec-ing out 15ish colours that are repeated elsewhere doesn't really 'feel' right. Even if if it's the simple way! :)

However, thanks for the reflection idea! I've finally got something that does exactly what I need. Here it is, for those who might be interested in a happy ending:
Code:
private Color getInputColor(String colorString) {
	try {
		Field field = Class.forName("java.awt.Color").getField(colorString);
		return (Color) field.get(field);
	} catch (Exception e) {
		return null;
	}
}
 
Back
Top Bottom