How It Works
There is a single HashMap in a Preferences object with a couple main methods; Preferences.get(String key) to retrieve any Object and Preferences.set(String key, Object value) to store anything that's changed. When set(key, object) is called, it will store and commit to a db4o database. The Preferences object is read in from the db4o database at startup and it is used to setup the application. If certain keys are not found in the Preferences HashMap, the default values are used.
Now every time the the app is restarted, the previous state can be restored with a simple db4o query asking for the Preferences object.
This is perhaps the easiest and most reliable way to store state across sessions for any desktop application. Plus you get the power of having a full-fledged object database at your disposable for storing all the other data in your application.
Why is this better than java.util.prefs ?
Because you can store objects, and it's much easier to use. Consider these comparisons:
- Store and retrieve a database connection
- With java.util.prefs, you'd have to store the connection url, username, and password in three different keys or as some string that you'd later have to parse, then probably put them in a DatabaseConnectionInfo object to use in your program.
- With db4o prefs, you just store the DatabaseConnectionInfo object, then retrieve the full object again.
- Storing frame size and location
- With java.util.prefs, you'd store "width", "height", "top", and "left" values, then you'd have to get each of those and put them into a Dimension and Point object.
- With db4o prefs, you store the Dimension and Point directly off the component and retrieve those directly back to set on the component.
- eg: on componentResized(ComponentEvent e){
Preferences.set("frameSize", e.getComponent().getSize()); - then on startup: frame.setSize(Preferences.get("frameSize"));
No comments:
Post a Comment