Following example shows how to use java.util.prefs to remember JFileChooser last location.
JFileChooser
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); } }
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; } }
The file location is remembered even after application restart.
Dependencies and Technologies Used: