Reputation: 2856
Currently I am doing:
private static JButton button;
button = new JButton();
button.setBackground(Color.RED);
This is giving my button a RED color.
I want a user set its color and the user entered color is stored in String color = "blue"
. I want something like button.setBackground(color);
so that it gives me the button
in blue
.
How do i do that?
Upvotes: 0
Views: 91
Reputation: 100050
Use the Color class to convert a string to a Color. You can use its methods to convert string representations to colors, or you can use reflection to find the reserved names. You could also consider the Swing color selector support. If you want to handle a rather random list of color names, you'll have to handle that for yourself as per Hovercraft's answeer.
Upvotes: 0
Reputation: 285403
The issue boils down to: how do you get a java.util.Color from a String. There are fancy ways of doing this directly from the Color class using reflection, but better to create a simple Map such as a HashMap<String, Color>
, so that you can associate your Strings with the corresponding Color. Then when you get the user's String in an ActionListener, you can use the Map to get the corresponding Color, and then use the Color when calling setBackground(...)
on your JButton.
Upvotes: 2