Reputation: 1016
I'm building a Swing application in Java and I want the colours to be consistent. So I could do something like:
public class Colours {
public static final String BACKGROUND = "#D9DADE";
}
But then I thought maybe an enum would be better, so I did this:
public enum ColourStyles {
BACKGROUND("#D9DADE");
private String colourValue;
private ColourStyles(String value) {
colourValue = value;
}
public String getColourValue() {
return colourValue;
}
};
But then that made the String now a ColourStyle type and I can't decode it using Color.decode(BACKGROUND)
.
Is there any better way of doing this completely, like a properties file? I've done Wicket but never come across the same sort of structure for labels/colours in Swing.
Thanks!
Upvotes: 1
Views: 120
Reputation: 14413
The 2 options are good, but i'd prefer a 3rd way and it's using a property file. So you don't have to recompile your application if you want to change.
1st)
public final class Colours {
private Colours(){}
public static final BACKGROUND = "#D9DADE";
}
. 2nd) It's ok, but you can add a method to the enum to return the color.
public enum ColourStyles {
BACKGROUND("#D9DADE");
private String colourValue;
private ColourStyles(String value) {
colourValue = value;
}
public String getColourValue() {
return colourValue;
}
public Color getColour(){
return Color.decode(colourValue);
}
}
And 3rd) create a file for example lookAndFeel.properties
colour.background=#D9DADE
Make a class that could be a singleton
to load the properties file and you can add a util method to return the colour like in the enum, the good thing of this is that you can change the values wihout compiling again your application.
4th) If you are using a customizable look&feel you can set that properties using UIManager.put();
to set properties for all components. Here is an example of properties for Nimbus L&F Nimbus defaults
Upvotes: 2