Search code examples
javapreferences

Java: Understanding Preferences


So I started using Preferences for the first time. For example:

JFrame frame = new JFrame("");
frame.addWindowListener(new WindowListener() {
        @Override
        public void windowClosing(WindowEvent e) {
            pref.put("LAST_WIDTH", "" + frame.getWidth());
            pref.put("LAST_HEIGHT", "" + frame.getHeight());
            System.exit(0);
        }

I encountered a problem when launching the application for the first time when I try to retrieve the last size.

if(pref.get("LAST_WIDTH", "") != null && pref.get("LAST_HEIGHT", "") != null){
        try{
            frame.setSize(Integer.parseInt(pref.get("LAST_WIDTH", "")), Integer.parseInt(pref.get("LAST_HEIGHT", "")));
        } catch(NumberFormatException e){
            frame.setSize(640, 480);
        }
    } else{
        frame.setSize(640, 480);
    }

Yes, I found a workaround with the try-catch, but I'd like to understand how preferences work. If I launch an application for the first time and try to retrieve a key that should not exist, what does preferences return?

Operating system is Windows 7 if that matters.


Solution

  • You are using it right in your example!

    String a = pref.get("key", "defaultValue");
    

    From the docs:

    Parameters:
        key - key whose associated value is to be returned.
        def - the value to be returned in the event that this preference node has no value associated with key.

    So in your case, replace the empty strings with your default values.

    frame.setSize(Integer.parseInt(pref.get("LAST_WIDTH", "640")), Integer.parseInt(pref.get("LAST_HEIGHT", "480")));