3

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319

3 Answers3

7

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.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • "-1: Work only for predefined color, not for user defined colors" - Aubin –  Mar 07 '13 at 22:01
  • 1
    +1 for `Map`; the reverse is suggested [here](http://stackoverflow.com/a/6717956/230513) for arbitrary [named colors](http://www.w3schools.com/html/html_colornames.asp). Also consider a [two-way map](http://stackoverflow.com/q/3430170/230513). – trashgod Mar 07 '13 at 22:36
  • 1
    @Legend, he could provide a method for registering user-defined colors -- by putting new values into the map. – shuangwhywhy Mar 07 '13 at 22:51
4

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.

  • 1
    -1: Work only for predefined color, not for user defined colors, reflection is not designed for this need even if your code sample compile and runs well. – Aubin Mar 07 '13 at 21:34
  • Eng.Fouad has done for me, nothing to add, it's perfect and upvoted – Aubin Mar 07 '13 at 21:52
  • Then you have nothing to contribute here. Also, last I checked, his only worked for predefined colors as well. –  Mar 07 '13 at 22:01
0

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

If("blue".equals(a)){
    jLabel3.setForeground(Color.blue);
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Boyen
  • 1,429
  • 2
  • 15
  • 22
  • And if we have 256 colors, you add 256*3 LOC every where you need a color? – Aubin Mar 07 '13 at 21:35
  • 1
    @Aubin Exactly, it's a very primitive way but it could be effective depending on how many different colors the user is allowed to use. – Boyen Mar 07 '13 at 21:37