System File Chooser:

- introduced state storage
- added "New Folder" to macOS select folder dialog
- Demo: added "Select Folder (System)" menu item
- javadoc fixes
This commit is contained in:
Karl Tauber
2025-03-22 13:51:16 +01:00
parent 3e8b213367
commit dade1cba5a
6 changed files with 275 additions and 14 deletions

View File

@@ -60,6 +60,10 @@ import com.formdev.flatlaf.ui.FlatNativeWindowsLibrary;
* {@code SystemFileChooser} requires FlatLaf native libraries (usually contained in flatlaf.jar).
* If not available or disabled (via {@link FlatSystemProperties#USE_NATIVE_LIBRARY}
* or {@link FlatSystemProperties#USE_SYSTEM_FILE_CHOOSER}), then {@code JFileChooser} is used.
* <p>
* To improve user experience, it is recommended to use a state storage
* (see {@link #setStateStore(StateStore)}), so that file dialogs open at previously
* visited folder.
*
* <h2>Limitations/incompatibilities compared to JFileChooser</h2>
*
@@ -90,6 +94,11 @@ import com.formdev.flatlaf.ui.FlatNativeWindowsLibrary;
* <li><b>macOS</b>: By default, the user can not navigate into file packages (e.g. applications).
* If needed, this can be enabled by setting platform property
* {@link #MAC_TREATS_FILE_PACKAGES_AS_DIRECTORIES} to {@code true}.
* <li>If no "current directory" is specified, then {@code JFileChooser} always opens
* the users "Documents" folder (on Windows) or "Home" folder (on macOS and Linux).<br>
* {@code SystemFileChooser} does the same when first shown, but then remembers
* last visited folder (either in memory or in a {@link StateStore}) and
* re-uses that folder when {@code SystemFileChooser} is shown again.
* </ul>
*
* @author Karl Tauber
@@ -248,6 +257,25 @@ public class SystemFileChooser
private Map<String, Object> platformProperties;
private static final StateStore inMemoryStateStore = new StateStore() {
private final Map<String, String> state = new HashMap<>();
@Override
public String get( String key, String def ) {
return state.getOrDefault( key, def );
}
@Override
public void put( String key, String value ) {
if( value != null )
state.put( key, value );
else
state.remove( key );
}
};
private static StateStore stateStore;
private String stateStoreID;
/** @see JFileChooser#JFileChooser() */
public SystemFileChooser() {
@@ -384,18 +412,35 @@ public class SystemFileChooser
/** @see JFileChooser#getCurrentDirectory() */
public File getCurrentDirectory() {
if( currentDirectory == null ) {
// get current directory from state store
StateStore store = (stateStore != null) ? stateStore : inMemoryStateStore;
String path = store.get( buildStateKey( StateStore.KEY_CURRENT_DIRECTORY ), null );
if( path != null )
currentDirectory = getTraversableDirectory( FileSystemView.getFileSystemView().createFileObject( path ) );
// for compatibility with JFileChooser
if( currentDirectory == null )
currentDirectory = getTraversableDirectory( FileSystemView.getFileSystemView().getDefaultDirectory() );
}
return currentDirectory;
}
/** @see JFileChooser#setCurrentDirectory(File) */
public void setCurrentDirectory( File dir ) {
// for compatibility with JFileChooser
if( dir != null && !dir.exists() )
return;
if( dir == null )
dir = FileSystemView.getFileSystemView().getDefaultDirectory();
currentDirectory = getTraversableDirectory( dir );
}
currentDirectory = dir;
private File getTraversableDirectory( File dir ) {
if( dir == null )
return null;
// make sure to use existing (traversable) directory
FileSystemView fsv = FileSystemView.getFileSystemView();
while( dir != null && !fsv.isTraversable( dir ) )
dir = fsv.getParentDirectory( dir );
return dir;
}
/** @see JFileChooser#getSelectedFile() */
@@ -533,7 +578,7 @@ public class SystemFileChooser
* Sets a callback that is invoked when user presses "OK" button (or double-clicks a file).
* The file dialog is still open.
* If the callback returns {@link #CANCEL_OPTION}, then the file dialog stays open.
* If it returns {@link #APPROVE_OPTION} (or any other value other than {@link #CANCEL_OPTION}),
* If it returns {@link #APPROVE_OPTION} (or any value other than {@link #CANCEL_OPTION}),
* the file dialog is closed and the {@code show...Dialog()} methods return that value.
* <p>
* The callback has two parameters:
@@ -562,9 +607,9 @@ public class SystemFileChooser
* }
* }</pre>
*
* <b>WARNING:</b> Do not show a Swing dialog for the callback. This will not work!
* <b>WARNING:</b> Do not show a Swing dialog from within the callback. This will not work!
* <p>
* Instead use {@link ApproveContext#showMessageDialog(int, String, String, int, String...)},
* Instead, use {@link ApproveContext#showMessageDialog(int, String, String, int, String...)},
* which shows a modal system message dialog as child of the file dialog.
*
* <pre>{@code
@@ -617,6 +662,43 @@ public class SystemFileChooser
return (value instanceof Integer) ? (Integer) value & ~optionsBlocked : 0;
}
/**
* Returns state storage used to persist file chooser state (e.g. last used directory).
* Or {@code null} if there is no state storage (the default).
*/
public static StateStore getStateStore() {
return stateStore;
}
/**
* Sets state storage used to persist file chooser state (e.g. last used directory).
*/
public static void setStateStore( StateStore stateStore ) {
SystemFileChooser.stateStore = stateStore;
}
/**
* Returns the ID used to prefix keys in state storage. Or {@code null} (the default).
*/
public String getStateStoreID() {
return stateStoreID;
}
/**
* Sets the ID used to prefix keys in state storage. Or {@code null} (the default).
* <p>
* By specifying an ID, an application can have different persisted states
* for different kinds of file dialogs within the application. E.g. Import/Export
* file dialogs could use a different ID then Open/Save file dialogs.
*/
public void setStateStoreID( String stateStoreID ) {
this.stateStoreID = stateStoreID;
}
private String buildStateKey( String key ) {
return (stateStoreID != null) ? stateStoreID + '.' + key : key;
}
private int showDialogImpl( Component parent ) {
Window owner = (parent instanceof Window)
? (Window) parent
@@ -627,7 +709,16 @@ public class SystemFileChooser
approveResult = APPROVE_OPTION;
File[] files = getProvider().showDialog( owner, this );
setSelectedFiles( files );
return (files != null) ? approveResult : CANCEL_OPTION;
if( files == null )
return CANCEL_OPTION;
// remember current directory in state store
File currentDirectory = getCurrentDirectory();
StateStore store = (stateStore != null) ? stateStore : inMemoryStateStore;
store.put( buildStateKey( StateStore.KEY_CURRENT_DIRECTORY ),
(currentDirectory != null) ? currentDirectory.getAbsolutePath() : null );
return approveResult;
}
private FileChooserProvider getProvider() {
@@ -870,7 +961,7 @@ public class SystemFileChooser
if( (optionsClear & FlatNativeMacLibrary.FC_accessoryViewDisclosed) == 0 )
optionsSet |= FlatNativeMacLibrary.FC_accessoryViewDisclosed;
if( fc.isDirectorySelectionEnabled() ) {
optionsSet |= FlatNativeMacLibrary.FC_canChooseDirectories;
optionsSet |= FlatNativeMacLibrary.FC_canChooseDirectories | FlatNativeMacLibrary.FC_canCreateDirectories;
optionsClear |= FlatNativeMacLibrary.FC_canChooseFiles;
open = true;
}
@@ -1335,4 +1426,26 @@ public class SystemFileChooser
public abstract int showMessageDialog( int messageType, String primaryText,
String secondaryText, int defaultButton, String... buttons );
}
//---- class StateStore ---------------------------------------------------
/**
* Simple state storage used to persist file chooser state (e.g. last used directory).
*
* @see SystemFileChooser#setStateStore(StateStore)
* @see SystemFileChooser#setStateStoreID(String)
*/
public interface StateStore {
String KEY_CURRENT_DIRECTORY = "currentDirectory";
/**
* Returns the value for the given key, or the default value if there is no value stored.
*/
String get( String key, String def );
/**
* Stores the given key and value. If value is {@code null}, it is removed from the store.
*/
void put( String key, String value );
}
}

View File

@@ -18,6 +18,7 @@ package com.formdev.flatlaf.demo;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -175,13 +176,19 @@ class DemoFrame
private void openSystemActionPerformed() {
SystemFileChooser chooser = new SystemFileChooser();
chooser.setMultiSelectionEnabled( true );
chooser.addChoosableFileFilter( new SystemFileChooser.FileNameExtensionFilter(
"Text Files", "txt", "md" ) );
chooser.addChoosableFileFilter( new SystemFileChooser.FileNameExtensionFilter(
"PDF Files", "pdf" ) );
chooser.addChoosableFileFilter( new SystemFileChooser.FileNameExtensionFilter(
"Archives", "zip", "tar", "jar", "7z" ) );
chooser.showOpenDialog( this );
if( chooser.showOpenDialog( this ) != SystemFileChooser.APPROVE_OPTION )
return;
File[] files = chooser.getSelectedFiles();
System.out.println( Arrays.toString( files ).replace( ",", "\n" ) );
}
private void saveAsSystemActionPerformed() {
@@ -190,7 +197,23 @@ class DemoFrame
"Text Files", "txt", "md" ) );
chooser.addChoosableFileFilter( new SystemFileChooser.FileNameExtensionFilter(
"Images", "png", "gif", "jpg" ) );
chooser.showSaveDialog( this );
if( chooser.showSaveDialog( this ) != SystemFileChooser.APPROVE_OPTION )
return;
File file = chooser.getSelectedFile();
System.out.println( file );
}
private void selectFolderSystemActionPerformed() {
SystemFileChooser chooser = new SystemFileChooser();
chooser.setFileSelectionMode( SystemFileChooser.DIRECTORIES_ONLY );
if( chooser.showOpenDialog( this ) != SystemFileChooser.APPROVE_OPTION )
return;
File directory = chooser.getSelectedFile();
System.out.println( directory );
}
private void exitActionPerformed() {
@@ -519,6 +542,7 @@ class DemoFrame
JMenuItem saveAsMenuItem = new JMenuItem();
JMenuItem openSystemMenuItem = new JMenuItem();
JMenuItem saveAsSystemMenuItem = new JMenuItem();
JMenuItem selectFolderSystemMenuItem = new JMenuItem();
JMenuItem closeMenuItem = new JMenuItem();
exitMenuItem = new JMenuItem();
JMenu editMenu = new JMenu();
@@ -630,6 +654,12 @@ class DemoFrame
saveAsSystemMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()|KeyEvent.SHIFT_DOWN_MASK));
saveAsSystemMenuItem.addActionListener(e -> saveAsSystemActionPerformed());
fileMenu.add(saveAsSystemMenuItem);
//---- selectFolderSystemMenuItem ----
selectFolderSystemMenuItem.setText("Select Folder (System)...");
selectFolderSystemMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()|KeyEvent.SHIFT_DOWN_MASK));
selectFolderSystemMenuItem.addActionListener(e -> selectFolderSystemActionPerformed());
fileMenu.add(selectFolderSystemMenuItem);
fileMenu.addSeparator();
//---- closeMenuItem ----

View File

@@ -197,6 +197,12 @@ new FormModel {
"accelerator": static javax.swing.KeyStroke getKeyStroke( 83, 4291, false )
addEvent( new FormEvent( "java.awt.event.ActionListener", "actionPerformed", "saveAsSystemActionPerformed", false ) )
} )
add( new FormComponent( "javax.swing.JMenuItem" ) {
name: "selectFolderSystemMenuItem"
"text": "Select Folder (System)..."
"accelerator": static javax.swing.KeyStroke getKeyStroke( 70, 4291, false )
addEvent( new FormEvent( "java.awt.event.ActionListener", "actionPerformed", "selectFolderSystemActionPerformed", false ) )
} )
add( new FormComponent( "javax.swing.JPopupMenu$Separator" ) {
name: "separator2"
} )

View File

@@ -17,6 +17,7 @@
package com.formdev.flatlaf.demo;
import java.awt.Dimension;
import java.util.prefs.Preferences;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
@@ -27,6 +28,7 @@ import com.formdev.flatlaf.fonts.inter.FlatInterFont;
import com.formdev.flatlaf.fonts.jetbrains_mono.FlatJetBrainsMonoFont;
import com.formdev.flatlaf.fonts.roboto.FlatRobotoFont;
import com.formdev.flatlaf.fonts.roboto_mono.FlatRobotoMonoFont;
import com.formdev.flatlaf.util.SystemFileChooser;
import com.formdev.flatlaf.util.SystemInfo;
/**
@@ -73,6 +75,28 @@ public class FlatLafDemo
DemoPrefs.init( PREFS_ROOT_PATH );
DemoPrefs.initSystemScale();
// SystemFileChooser state storage
SystemFileChooser.setStateStore( new SystemFileChooser.StateStore() {
private static final String KEY_PREFIX = "fileChooser.";
private final Preferences state = Preferences.userRoot().node( PREFS_ROOT_PATH );
@Override
public String get( String key, String def ) {
String value = state.get( KEY_PREFIX + key, def );
System.out.println( "SystemFileChooser State GET " + key + " = " + value );
return value;
}
@Override
public void put( String key, String value ) {
System.out.println( "SystemFileChooser State PUT " + key + " = " + value );
if( value != null )
state.put( KEY_PREFIX + key, value );
else
state.remove( KEY_PREFIX + key );
}
} );
SwingUtilities.invokeLater( () -> {
// install fonts for lazy loading
FlatInterFont.installLazy();

View File

@@ -89,10 +89,39 @@ public class FlatSystemFileChooserTest
currentDirCheckBox.setSelected( state.getBoolean( "systemfilechooser.currentdir.enabled", false ) );
selectedFileCheckBox.setSelected( state.getBoolean( "systemfilechooser.selectedfile.enabled", false ) );
selectedFilesCheckBox.setSelected( state.getBoolean( "systemfilechooser.selectedfiles.enabled", false ) );
persistStateCheckBox.setSelected( state.getBoolean( "systemfilechooser.persistState.enabled", false ) );
currentDirChanged();
selectedFileChanged();
selectedFilesChanged();
persistStateChanged();
}
private void persistStateChanged() {
boolean b = persistStateCheckBox.isSelected();
SystemFileChooser.setStateStore( b
? new SystemFileChooser.StateStore() {
private static final String KEY_PREFIX = "fileChooser.";
@Override
public String get( String key, String def ) {
String value = DemoPrefs.getState().get( KEY_PREFIX + key, def );
System.out.println( "GET " + key + " = " + value );
return value;
}
@Override
public void put( String key, String value ) {
System.out.println( "PUT " + key + " = " + value );
if( value != null )
DemoPrefs.getState().put( KEY_PREFIX + key, value );
else
DemoPrefs.getState().remove( KEY_PREFIX + key );
}
} : null );
DemoPrefs.getState().putBoolean( "systemfilechooser.persistState.enabled", b );
}
private void open() {
@@ -221,6 +250,9 @@ public class FlatSystemFileChooserTest
// fc.putPlatformProperty( SystemFileChooser.MAC_OPTIONS_CLEAR, FlatNativeMacLibrary.FC_showsTagField );
// fc.putPlatformProperty( SystemFileChooser.LINUX_OPTIONS_CLEAR, FlatNativeLinuxLibrary.FC_create_folders | FlatNativeLinuxLibrary.FC_do_overwrite_confirmation );
String id = (String) stateStoreIDField.getSelectedItem();
fc.setStateStoreID( id != null && !id.isEmpty() ? id : null );
}
private void configureSwingFileChooser( JFileChooser fc ) {
@@ -517,6 +549,9 @@ public class FlatSystemFileChooserTest
multiSelectionEnabledCheckBox = new JCheckBox();
useFileHidingCheckBox = new JCheckBox();
useSystemFileChooserCheckBox = new JCheckBox();
persistStateCheckBox = new JCheckBox();
JLabel stateStoreIDLabel = new JLabel();
stateStoreIDField = new JComboBox<>();
JLabel approveButtonTextLabel = new JLabel();
approveButtonTextField = new JTextField();
JLabel approveButtonMnemonicLabel = new JLabel();
@@ -605,6 +640,8 @@ public class FlatSystemFileChooserTest
"[]0" +
"[]0" +
"[]" +
"[]para" +
"[]" +
"[]"));
//---- directorySelectionCheckBox ----
@@ -624,6 +661,24 @@ public class FlatSystemFileChooserTest
useSystemFileChooserCheckBox.setText("use SystemFileChooser");
useSystemFileChooserCheckBox.setSelected(true);
panel1.add(useSystemFileChooserCheckBox, "cell 0 3");
//---- persistStateCheckBox ----
persistStateCheckBox.setText("persist state");
persistStateCheckBox.addActionListener(e -> persistStateChanged());
panel1.add(persistStateCheckBox, "cell 0 4");
//---- stateStoreIDLabel ----
stateStoreIDLabel.setText("ID:");
panel1.add(stateStoreIDLabel, "cell 0 5");
//---- stateStoreIDField ----
stateStoreIDField.setModel(new DefaultComboBoxModel<>(new String[] {
"abc",
"def"
}));
stateStoreIDField.setEditable(true);
stateStoreIDField.setSelectedIndex(-1);
panel1.add(stateStoreIDField, "cell 0 5,growx");
}
add(panel1, "cell 2 1 1 7,aligny top,growy 0");
@@ -806,6 +861,8 @@ public class FlatSystemFileChooserTest
private JCheckBox multiSelectionEnabledCheckBox;
private JCheckBox useFileHidingCheckBox;
private JCheckBox useSystemFileChooserCheckBox;
private JCheckBox persistStateCheckBox;
private JComboBox<String> stateStoreIDField;
private JTextField approveButtonTextField;
private JTextField approveButtonMnemonicField;
private JCheckBox currentDirCheckBox;

View File

@@ -71,7 +71,7 @@ new FormModel {
add( new FormContainer( "javax.swing.JPanel", new FormLayoutManager( class net.miginfocom.swing.MigLayout ) {
"$layoutConstraints": "insets 2,hidemode 3"
"$columnConstraints": "[left]"
"$rowConstraints": "[]0[]0[][]"
"$rowConstraints": "[]0[]0[][]para[][]"
} ) {
name: "panel1"
add( new FormComponent( "javax.swing.JCheckBox" ) {
@@ -112,6 +112,37 @@ new FormModel {
}, new FormLayoutConstraints( class net.miginfocom.layout.CC ) {
"value": "cell 0 3"
} )
add( new FormComponent( "javax.swing.JCheckBox" ) {
name: "persistStateCheckBox"
"text": "persist state"
auxiliary() {
"JavaCodeGenerator.variableLocal": false
}
addEvent( new FormEvent( "java.awt.event.ActionListener", "actionPerformed", "persistStateChanged", false ) )
}, new FormLayoutConstraints( class net.miginfocom.layout.CC ) {
"value": "cell 0 4"
} )
add( new FormComponent( "javax.swing.JLabel" ) {
name: "stateStoreIDLabel"
"text": "ID:"
}, new FormLayoutConstraints( class net.miginfocom.layout.CC ) {
"value": "cell 0 5"
} )
add( new FormComponent( "javax.swing.JComboBox" ) {
name: "stateStoreIDField"
"model": new javax.swing.DefaultComboBoxModel {
selectedItem: "abc"
addElement( "abc" )
addElement( "def" )
}
"editable": true
"selectedIndex": -1
auxiliary() {
"JavaCodeGenerator.variableLocal": false
}
}, new FormLayoutConstraints( class net.miginfocom.layout.CC ) {
"value": "cell 0 5,growx"
} )
}, new FormLayoutConstraints( class net.miginfocom.layout.CC ) {
"value": "cell 2 1 1 7,aligny top,growy 0"
} )