kf-manager/src/main/java/cz/kamma/kfmanager/ui/FileChooserUtils.java
2026-01-30 13:49:26 +01:00

74 lines
2.9 KiB
Java

package cz.kamma.kfmanager.ui;
import cz.kamma.kfmanager.config.AppConfig;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class FileChooserUtils {
public static int showOpenDialog(Component parent, JFileChooser chooser, AppConfig config) {
return showDialog(parent, chooser, config, true);
}
public static int showSaveDialog(Component parent, JFileChooser chooser, AppConfig config) {
return showDialog(parent, chooser, config, false);
}
private static int showDialog(Component parent, JFileChooser chooser, AppConfig config, boolean open) {
// Set initial directory only if not already set or points to home
File current = chooser.getCurrentDirectory();
if (current == null || current.getAbsolutePath().equals(System.getProperty("user.home"))) {
String lastDir = config.getLastFileChooserDirectory();
if (lastDir != null && !lastDir.isEmpty()) {
File dir = new File(lastDir);
if (dir.exists() && dir.isDirectory()) {
chooser.setCurrentDirectory(dir);
}
}
}
final JDialog[] dialogRef = {null};
HierarchyListener hierarchyListener = new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && chooser.isShowing()) {
Window window = SwingUtilities.getWindowAncestor(chooser);
if (window instanceof JDialog dialog) {
dialogRef[0] = dialog;
// Restore size and position
int w = config.getFileChooserWidth();
int h = config.getFileChooserHeight();
if (w > 0 && h > 0) dialogRef[0].setSize(w, h);
int x = config.getFileChooserX();
int y = config.getFileChooserY();
if (x >= 0 && y >= 0) {
dialogRef[0].setLocation(x, y);
} else {
dialogRef[0].setLocationRelativeTo(parent);
}
}
}
}
};
chooser.addHierarchyListener(hierarchyListener);
int result = open ? chooser.showOpenDialog(parent) : chooser.showSaveDialog(parent);
chooser.removeHierarchyListener(hierarchyListener);
if (dialogRef[0] != null) {
config.setFileChooserBounds(dialogRef[0].getX(), dialogRef[0].getY(), dialogRef[0].getWidth(), dialogRef[0].getHeight());
}
File currentDir = chooser.getCurrentDirectory();
if (currentDir != null) {
config.setLastFileChooserDirectory(currentDir.getAbsolutePath());
}
config.saveConfig();
return result;
}
}