Close

Java Swing - Remembering JFileChooser Location by using Java Util Preferences API

[Last Updated: Jul 4, 2018]

Following example shows how to use java.util.prefs to remember JFileChooser last location.

Using Preferences

Following is a helper enum class which does Preferences API handling:

package com.logicbig.example;

import java.util.prefs.Preferences;

public enum AppPrefs {
    FileLocation;
    private static Preferences prefs = Preferences.userRoot()
                                          .node(AppPrefs.class.getName());

    String get(String defaultValue) {
        return prefs.get(this.name(), defaultValue);
    }

    void put(String value) {
        prefs.put(this.name(), value);
    }
}

Main class

public class ExampleMain {
    public static void main(String[] args) {
        JFrame frame = createFrame();
        JLabel fileLabel = new JLabel();

        JButton openFileBtn = new JButton("Open File");
        openFileBtn.addActionListener(ae -> chooseFile(fileLabel, frame));

        JPanel panel = new JPanel();
        panel.add(openFileBtn);
        frame.add(panel, BorderLayout.NORTH);
        frame.add(fileLabel);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static void chooseFile(JLabel fileLabel, JFrame frame) {
        JFileChooser fileChooser = new JFileChooser();
        String location = AppPrefs.FileLocation.get(System.getProperty("user.home"));
        fileChooser.setCurrentDirectory(new File(location));

        int returnValue = fileChooser.showOpenDialog(frame);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            fileLabel.setText(selectedFile.getAbsolutePath());
            AppPrefs.FileLocation.put(selectedFile.getParentFile().getAbsolutePath());
        }
    }

    private static JFrame createFrame() {
        JFrame frame = new JFrame("JTree Remembering File Chooser location via Java Prefs");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(500, 400));
        return frame;
    }
}

Output

The file location is remembered even after application restart.

Example Project

Dependencies and Technologies Used:

  • JDK 10
  • Maven 3.5.4

Remembering JFileChooser Location by using Preferences Select All Download
  • java-prefs-remembering-file-dialog-location
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java

    See Also