Implemented saving the last accessed file system path

When loading or saving a game file, the file chooser dialog opens inside
the directory that has been last accessed by the user. In case of no
previous access, the home directory is used instead.

Closes #14
This commit is contained in:
Kai S. K. Engelbart 2019-12-11 22:08:43 +01:00
parent 9a4d9121de
commit d46a9aa5ff
Signed by: kske
GPG Key ID: 8BEB13EC5DF7EF13

View File

@ -9,6 +9,7 @@ import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.prefs.Preferences;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
@ -32,22 +33,34 @@ public class DialogUtil {
private DialogUtil() {}
/**
* Saves the last accessed folder for loading and saving game files.
*/
private static Preferences preferences = Preferences.userNodeForPackage(DialogUtil.class);
public static void showFileSelectionDialog(Component parent, Consumer<List<File>> action, Collection<FileNameExtensionFilter> filters) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setAcceptAllFileFilterUsed(false);
filters.forEach(fileChooser::addChoosableFileFilter);
if (fileChooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) action.accept(Arrays.asList(fileChooser.getSelectedFile()));
JFileChooser fileChooser = createFileChooser(filters);
if (fileChooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
action.accept(Arrays.asList(fileChooser.getSelectedFile()));
preferences.put("path", fileChooser.getSelectedFile().getParent());
}
}
public static void showFileSaveDialog(Component parent, Consumer<File> action, Collection<FileNameExtensionFilter> filters) {
JFileChooser fileChooser = createFileChooser(filters);
if (fileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
action.accept(new File(fileChooser.getSelectedFile().getAbsolutePath() + "."
+ ((FileNameExtensionFilter) fileChooser.getFileFilter()).getExtensions()[0]));
preferences.put("path", fileChooser.getSelectedFile().getParent());
}
}
private static JFileChooser createFileChooser(Collection<FileNameExtensionFilter> filters) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setCurrentDirectory(new File(preferences.get("path", System.getProperty("user.home"))));
fileChooser.setAcceptAllFileFilterUsed(false);
filters.forEach(fileChooser::addChoosableFileFilter);
if (fileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) action.accept(
new File(fileChooser.getSelectedFile().getAbsolutePath() + "."
+ ((FileNameExtensionFilter) fileChooser.getFileFilter()).getExtensions()[0]));
return fileChooser;
}
public static void showGameConfigurationDialog(Component parent, BiConsumer<String, String> action) {