The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.prefs  [18 examples] > Events  [2 examples]

e421. Listening for Changes to Preference Values in a Preference Node

A PreferenceChangeEvent is fired when a preference is added, changed, or removed from a preference node. This event is only guaranteed to fire if the listener and modifier are in the same application. This event is not fired if the node is removed.

See also e422 Determining When a Preference Node Is Added or Removed.

    // Retrieve the user preference node for the package java.lang
    Preferences prefs = Preferences.userNodeForPackage(String.class);
    
    // Register the listener
    prefs.addPreferenceChangeListener(new PreferenceChangeListener() {
        public void preferenceChange(PreferenceChangeEvent evt) {
            // Get the node that changed
            Preferences node = evt.getNode();
    
            // Get the affected key.
            // Note: it is not possible to tell if the key was new
            // or its value was changed.
            String key = evt.getKey();
    
            // Get the new value; if the new value is null,
            // the preference was removed
            String newValue = evt.getNewValue();
        }
    });
    
    // Add a preference
    prefs.put("key", "a string");
    
    // Modify the preference
    prefs.put("key", "a new string");
    
    // Remove the preference
    prefs.remove("key");

 Related Examples
e422. Determining When a Preference Node Is Added or Removed

See also: Importing and Exporting    Nodes   


© 2002 Addison-Wesley.