Set Color of JLabel Using a String

colors, foreground, java, jlabel, swing

Solution

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.

Problem

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.

Original source

Related problems