# Java: Preferences

The `java.util.pref.Preferences` class, which was added in Java 1.4 to provide improved functionality over the `java.util.Properties` class, is used to store and get persistent (remains on disk between program executions) hierarchical name/values pairs. These preferences are stored in an operating system dependent manner, eg in the Windows registry, a Mac preferences file, or in a Unix do file. Both system and user preferences can be obtained.

The method of using Preferences described below gets and maniupates a Preference object associated with the class of the current application, which gives each program a unique set of preferences.

## Description

The following is only a summary of a few methods that use String values and are all at the level of the current program. Preferences can be hierarchical and support primitive values in addition to String.

java.util.pref.Preferences - Used to maintain persistent key/value pairs.
prefs = | Preferences.userNodeForPackage(this.getClass());
|  | Gets or create a new Preferences object associated with this program.
| prefs.clear(); | Clears all preferences for this Preference object.
| prefs.flush(); | Writes preferences to persistent storage (eg, disk). Not needed if program terminates normally. Can throw `java.util.prefs.BackingStoreException` exception.
| prefs.set(key, s); | Associates string value s with string key key
sval = | prefs.get(key, defVal); | Returns value associated with String key or the default value, defVal, if there is no value for that key.
keyArray = | prefs.keys(); | Returns String array of all keys in the current Preferences object.
| prefs.remove(key); | Returns value associated with string key.

## Example

The following program illustrates the getting and saving of user name/value pairs.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    /**
      * PrefTest.java - A simple program to top-level user preferences.
      * @version 2004-04-18 Rodenbach
      * @author Fred Swartz
    */

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;

    import java.util.prefs.Preferences;
    import java.util.prefs.BackingStoreException;

    /////////////////////////////////////////////////////////////////// PrefTest
    class PrefTest extends JFrame {
        private JTextField _nameField = new JTextField(8);
        private JTextField _valueField= new JTextField(8);
        private JList      _prefList  = new JList(new String[] {});
        private Preferences _prefs;

        //========================================================== constructor
        PrefTest() {
            _prefs = Preferences.userNodeForPackage(this.getClass());
            setListFromPrefs();

            //-- Create and set attributes of widgets.
            JScrollPane scrollingList = new JScrollPane(_prefList);
            JButton newKeyButton = new JButton("Put Key/Value");
            JButton clearButton = new JButton("Clear All");
            JButton delSelectedButton = new JButton("Remove Selected");

            //-- Set action listeners.
            newKeyButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (_nameField.getText().length() > 0) {
                        _prefs.put(_nameField.getText(), _valueField.getText());
                        _nameField.setText("");   // Clear fields after saving.
                        _valueField.setText("");
                        setListFromPrefs();  // Update display
                    } else {
                        _nameField.setText("Key?");
                    }
                }});

            clearButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        _prefs.clear();
                        setListFromPrefs();  // Update display
                    } catch (BackingStoreException ex) {
                        System.out.println(ex);
                    }
                }});

            delSelectedButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String selection = (String)_prefList.getSelectedValue();
                    if (selection != null) {
                        String key = selection.substring(0, selection.indexOf("="));
                        _prefs.remove(key);  // Remove the selected key.
                        setListFromPrefs();  // Update display
                    }
                }});
            //-- Layout widgets.
            JPanel buttonPanel = new JPanel(new FlowLayout());
            buttonPanel.add(newKeyButton);
            buttonPanel.add(new JLabel("Key"));
            buttonPanel.add(_nameField);
            buttonPanel.add(new JLabel("Value"));
            buttonPanel.add(_valueField);
            buttonPanel.add(delSelectedButton);
            buttonPanel.add(clearButton);

            JPanel content = new JPanel(new BorderLayout());
            content.add(buttonPanel  , BorderLayout.NORTH);
            content.add(scrollingList, BorderLayout.CENTER);

            this.setContentPane(content);
            this.pack();
        }//end constructor

        //===================================================== setListFromPrefs
        private void setListFromPrefs() {
            try {
                String[] keys = _prefs.keys();
                for (int i=0; i<keys.length; i++) {
                    keys[i] += "=" + _prefs.get(keys[i], "ERROR");
                }
                _prefList.setListData(keys);
            } catch (BackingStoreException ex) {
                System.out.println(ex);
            }
        }

        //================================================================= main
        public static void main(String[] args) {
            JFrame window = new PrefTest();
            window.setTitle("PrefTest");
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.show();
        }//end main

    }//end class PrefTest