Reputation: 93
The Preference put
and get
methods require and return string values, but I need to work with objects (colours), i.e.
Preferences prefs = Preferences.userNodeForPackage(getClass());
prefs.put("savedColour", "red");
Color c = prefs.get("savedColour", "black");
Obviously there's a type mismatch on that last line, but I can't store the actual colour in prefs either,
prefs.put("savedColour", Color.RED)
because you need to store it as a string (or int, but not colour).
Any solutions to this? Only thing that comes to mind is very messy.
Upvotes: 0
Views: 497
Reputation: 4328
There is a way to store an object in your preferences, but it takes a few steps. You can convert your object into a byte array, break it into pieces in a 2D byte array, then store the byte arrays into the slots of a single node. Here is a step-by-step example on how to do it:
http://www.ibm.com/developerworks/library/j-prefapi/
Upvotes: 0
Reputation: 336
Convert color value into hexadecimal value and then store it as a string. While retrieving it decode hexadecimal value into string.
public static String getColorString(Color c) {
int i = c.getRGB() & 0xFFFFFF;
String s = Integer.toHexString(i).toUpperCase();
while (s.length() < 6) {
s = "0" + s;
}
return s;
}
public static void putColor(Preferences node, String key, Color c) {
node.put(key, "0x" + getColorString(c));
}
public static Color getColor(Preferences node, String key, Color default_color) {
Color result = default_color;
String value = node.get(key, "unknown");
if (!value.equals("unknown")) {
try {
result = Color.decode(value);
} catch (Exception e) {
System.out.println("Couldn't decode color preference for '" + key + "' from '" + value + "'");
}
}
return result;
}
Upvotes: 0
Reputation: 449
If essentially "serializing" the objects themselves is a requirement, perhaps using an alternate system to the Preferences API like Xstream or Google Gson might be an option to "save" the objects to disk.
This would be more complex than just using the Preferences API, mind you, and if it's possble to store the object information as Tichodroma describes is possible I'd probably do that, but do you gain the increased flexibility of being able to represent the objects your interested in as more than just Strings.
You could even use it complementary to the Preferences API so that only the more complex objects are serialized, and the basics are kept in the Preferences format.
Upvotes: 1
Reputation:
Perhaps you can add a constructor to you Color
class that takes a String and builds the Color
instance.
public Color(String nameOfColor) {
// do stuff
}
In addition you should implement the toString()
method for the Color
class.
Upvotes: 1