Robert Kuramshin
Robert Kuramshin

Reputation: 33

Set Color of JLabel Using a String

I am working on a Java project. I want for the user to input a color for a Label. I want to do something like this, but with a String.

jLabel3.setForeground(Color.blue);

Here is what I tried, but didn't work:

String a = "blue";
jLabel3.setForeground(Color.a);

or:

String a = "blue";
jLabel3.setForeground(a);

Is there possibly another way to do this with a method? Any help would be great. Thank You.

Upvotes: 3

Views: 2238

Answers (3)

Eng.Fouad
Eng.Fouad

Reputation: 117587

Here is one way:

Map<String, Color> colors = new HashMap<String, Color>();

// ...

colors.put("blue", Color.BLUE);
colors.put("red", Color.RED);
colors.put("green", Color.GREEN);
// other colors

Then use it like:

String a = "blue";
jLabel3.setForeground(colors.get(a.toLowerCase()));

EDIT: Consider a color chooser. See How to Use Color Choosers.

Upvotes: 7

Boyen
Boyen

Reputation: 1549

Not sure if there is a better way but you could do somthing like:

If("blue".equals(a)){
    jLabel3.setForeground(Color.blue);
}

Upvotes: 0

user1181445
user1181445

Reputation:

Try reflection:

Color color;
try {
    Field field = Class.forName("java.awt.Color").getField("yellow");
    color = (Color)field.get(null);
} catch (final Exception e) {
    e.printStackTrace();
}

Besides that you can create a map of colors and their names.

Upvotes: 4

Related Questions