A frame that restores position and size from user preferences and updates the preferences upon exit : Preference Properties « Development Class « Java

A frame that restores position and size from user preferences and updates the preferences upon exit

   This program is a part of the companion code for Core Java 8th ed.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.prefs.Preferences;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

 * A program to test preference settings. The program remembers the frame position, size, and title.
 * @version 1.02 2007-06-12
 * @author Cay Horstmann
public class PreferencesTest
   public static void main(String[] args)
      EventQueue.invokeLater(new Runnable()
            public void run()
               PreferencesFrame frame = new PreferencesFrame();

 * A frame that restores position and size from user preferences and updates the preferences upon
 * exit.
class PreferencesFrame extends JFrame
   public PreferencesFrame()
      // get position, size, title from preferences

      Preferences root = Preferences.userRoot();
      final Preferences node = root.node("/com/horstmann/corejava");
      int left = node.getInt("left", 0);
      int top = node.getInt("top", 0);
      int width = node.getInt("width", DEFAULT_WIDTH);
      int height = node.getInt("height", DEFAULT_HEIGHT);
      setBounds(left, top, width, height);

      // if no title given, ask user

      String title = node.get("title", "");
      if (title.equals("")) title = JOptionPane.showInputDialog("Please supply a frame title:");
      if (title == null) title = "";

      // set up file chooser that shows XML files

      final JFileChooser chooser = new JFileChooser();
      chooser.setCurrentDirectory(new File("."));

      // accept all files ending with .xml
      chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
            public boolean accept(File f)
               return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();

            public String getDescription()
               return "XML files";

      // set up menus
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("File");

      JMenuItem exportItem = new JMenuItem("Export preferences");
      exportItem.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent event)
               if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
                     OutputStream out = new FileOutputStream(chooser.getSelectedFile());
                  catch (Exception e)

      JMenuItem importItem = new JMenuItem("Import preferences");
      importItem.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent event)
               if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
                     InputStream in = new FileInputStream(chooser.getSelectedFile());
                  catch (Exception e)

      JMenuItem exitItem = new JMenuItem("Exit");
      exitItem.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent event)
               node.putInt("left", getX());
               node.putInt("top", getY());
               node.putInt("width", getWidth());
               node.putInt("height", getHeight());
               node.put("title", getTitle());

   public static final int DEFAULT_WIDTH = 300;
   public static final int DEFAULT_HEIGHT = 200;


Related examples in the same category

1.Put key value pair to PreferencePut key value pair to Preference
2.Get childrenNames from PreferencesGet childrenNames from Preferences
3.Get keys from PreferencesGet keys from Preferences
4.Get name and parent from PreferenceGet name and parent from Preference
5.Get node from PreferenceGet node from Preference
6.Get value from PreferencesGet value from Preferences
7.Export Preferences to XML fileExport Preferences to XML file
8.Passing references aroundPassing references around
9.Retrieve the preference node using a Class object and saves and retrieves a preference in the node.
10.Determining If a Preference Node Contains a Specific Key
11.Determining If a Preference Node Contains a Specific Value
12.Removing a Preference from a Preference Node
13.Getting and Setting Java Type Values in a Preference
14.Getting the Maximum Size of a Preference Key and Value
15.Getting the Roots of the Preference Trees
16.Retrieving a Preference Node
17.Removing a Preference Node
18.Determining If a Preference Node Exists
19.Retrieving the Parent and Child Nodes of a Preference Node
20.Exporting the Preferences in a Preference Node
21.Exporting the Preferences in a Subtree of Preference Nodes
22.Determining When a Preference Node Is Added or Removed
23.Read / write data in Windows registry
24.Listening for Changes to Preference Values in a Preference Node
25.Saving Data with the Preferences APISaving Data with the Preferences API
26.Preference Example:: export To FilePreference Example:: export To File
27.Properties load
28.Properties TreeMap and StreamProperties TreeMap and Stream
29.Parse Properties FilesParse Properties Files
30.Preferences DemoPreferences Demo
31.Properties TestProperties Test
32.Sort Properties when saving
33.Loading configuration parameters from text file based properties
34.To read a Properties file via an Applet
35.A Properties file stored in a JAR can be loaded this way
36.Load a properties file in the startup directory
37.Have a multi-line value in a properties file
38.Convert a Properties list into a map.
39.Listing All System Properties
40.Getting and Setting Properties
41.Use XML with Properties
42.Store properties as XML file
43.Reading and Writing a Properties File
44.Read system property as an integer
45.Read a configuration file using java.util.Properties
46.Load properties from XML file
47.Here is an example of the contents of a properties file:
48.Use the Registry to store informations (Preferences API)
49.Load a properties file in the classpath
50.Listing the system properties
51.Properties Demo
52.PropsToXML takes a standard Java properties file, and converts it into an XML file
53.Utility class for preferences
54.Static methods for retrieving and system properties and converting them to various types
55.Store recent items (e.g. recent file in a menu or recent search text in a search dialog)
56.Storing/loading Preferences
57.A frame that restores position and size from a properties file and updates the properties upon exitA frame that restores position and size from a properties file and updates the properties upon exit
58.A simple Properties extension easing the loading and saving of data