A Java Preferences API example/tutorial

Using the Java Preferences API couldn’t be much easier. In a Swing application I was just working on I wanted to remember the last output directory a user accessed, and the following steps show all that I had to do:

Step 1: Import the Java Preferences package:

import java.util.prefs.*;

Step 2:  Create a Java Preferences reference

Next, just create a Preferences object instance. I usually do this in a main class, main controller, or a “preferences controller,” depending on the size of the application:

// declare my variable at the top of my Java class
private Preferences prefs;

// create a Preferences instance (somewhere later in the code)
prefs = Preferences.userNodeForPackage(this.getClass());

Step 3: Set the preference when a desired action occurs

In the next section of code I’m going to “remember” the last directory a user selected when the user presses a button. I don’t have a screen shot here, but the UI looks like a typical file/directory selection widget, with a textfield and a lookup button next to each other.

void outputDirectoryButton_actionPerformed(ActionEvent e)
{
  int status = getDirectoryFromUser(jFileChooser,mostRecentOutputDirectory);
  if ( status == JFileChooser.APPROVE_OPTION )
  {
    mostRecentOutputDirectory = jFileChooser.getSelectedFile();
    jspOutputDirectoryTextField.setText(mostRecentOutputDirectory.getAbsolutePath());
    prefs.put("LAST_OUTPUT_DIR", mostRecentOutputDirectory.getAbsolutePath());
  }
}

Step 4: Get the reference to pre-populate a textfield the next time the user comes to the desired data entry screen

Now, whenever the user comes back to the UI again, I can pre-populate the textfield with the last directory they chose, using the code below:

String lastOutputDir = prefs.get("LAST_OUTPUT_DIR", "");
outputDirectoryTextField.setText(lastOutputDir);

Java Preferences - verification

To see what the Preferences API is doing for me, I looked at my Windows registry with regedit. The key name that was created for me is:

HKEY_CURRENT_USER\Software\JavaSoft\Prefs\com\devdaily\jrad 

When I poke through the registry and get to this node, I find my “LAST_OUTPUT_DIR” key.

Again, this is pretty simple and straightforward, and I encourage you to use the Preferences API to do things like this that make your application more user-friendly.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.