JavaFX FileChooser可以“记住”它打开的最后一个目录吗?

我的视图控制器有一个FileChooser实例,用于打开和保存文件.

每次我从该实例调用showOpenDialog()或showSaveDialog()时,我希望生成的对话框与我上次调用其中一个时离开它时在同一目录中.

相反,每次我调用其中一个方法时,对话框都会在用户主目录中打开.

如何使对话框的“当前目录”在不同的调用中保持不变?

当前行为的示例:

import java.io.File;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 * Demonstrates the use of an open dialog.
 * 
 * @author N99x
 */
public class FileChooserTest extends Application {

    private final FileChooser open = new FileChooser();
    private File lastOpened = null;

    @Override
    public void start(Stage primaryStage) {
        Label lbl = new Label("File Opened: <null>");
        lbl.setPadding(new Insets(8));
        Button btn = new Button();
        btn.setPadding(new Insets(8));
        btn.setText("Open");
        btn.setOnAction((ActionEvent event) -> {
            open.setInitialDirectory(lastOpened);
            File selected = open.showOpenDialog(primaryStage);
            if (selected == null) {
                lbl.setText("File Opened: <null>");
                // lastOpened = ??;
            } else {
                lbl.setText("File Opened: " + selected.getAbsolutePath());
                lastOpened = selected.getParentFile();
            }
        });

        VBox root = new VBox(lbl,btn);
        root.setPadding(new Insets(8));
        root.setAlignment(Pos.TOP_CENTER);
        Scene scene = new Scene(root,300,300);

        primaryStage.setTitle("FileChooser Testing!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

我设法通过存储打开的值来解决部分问题,但是如果关闭或取消对话框,这不起作用.

解决方法

How do I make the “current directory” of the dialogs persist across
different invocations?

您可以为此修改Singleton Pattern方法

因此,您只能使用一个FileChooser并监视/控制那里的初始目录,但不会直接将该实例暴露给类外的修改

例如:

public class RetentionFileChooser {
    private static FileChooser instance = null;
    private static SimpleObjectProperty<File> lastKnownDirectoryProperty = new SimpleObjectProperty<>();

    private RetentionFileChooser(){ }

    private static FileChooser getInstance(){
        if(instance == null) {
            instance = new FileChooser();
            instance.initialDirectoryProperty().bindBidirectional(lastKnownDirectoryProperty);
            //Set the FileExtensions you want to allow
            instance.getExtensionFilters().setAll(new ExtensionFilter("png files (*.png)","*.png"));
        }
        return instance;
    }

    public static File showOpenDialog(){
        return showOpenDialog(null);
    }

    public static File showOpenDialog(Window ownerWindow){
        File chosenFile = getInstance().showOpenDialog(ownerWindow);
        if(chosenFile != null){
            //Set the property to the directory of the chosenFile so the fileChooser will open here next
            lastKnownDirectoryProperty.setValue(chosenFile.getParentFile());
        }
        return chosenFile;
    }

    public static File showSaveDialog(){
        return showSaveDialog(null);
    }

    public static File showSaveDialog(Window ownerWindow){
        File chosenFile = getInstance().showSaveDialog(ownerWindow);
        if(chosenFile != null){
            //Set the property to the directory of the chosenFile so the fileChooser will open here next
            lastKnownDirectoryProperty.setValue(chosenFile.getParentFile());
        }
        return chosenFile;
    }
}

这将把FileChooser的初始目录设置为用户上次重新打开/保存的文件的目录

用法示例:

File chosenFile = RetentionFileChooser.showOpenDialog();

但是这里有一个限制:

//Set the FileExtensions you want to allow 
instance.getExtensionFilters().setAll(new ExtensionFilter("png files (*.png)","*.png"));

由于没有提供任何ExtensionFilter,FileChooser变得不那么用户友好,要求用户手动附加文件类型,但在创建实例时提供过滤器而无法更新它们将其限制为相同的过滤器

改进这一点的一种方法是在RetentionFileChooser中公开可以使用varargs提供的可选过滤器,从而可以在显示对话框时选择修改过滤器的时间

例如,建立在前一个:

public class RetentionFileChooser {
    public enum FilterMode {
        //Setup supported filters
        PNG_FILES("png files (*.png)","*.png"),TXT_FILES("txt files (*.txt)","*.txt");

        private ExtensionFilter extensionFilter;

        FilterMode(String extensionDisplayName,String... extensions){
            extensionFilter = new ExtensionFilter(extensionDisplayName,extensions);
        }

        public ExtensionFilter getExtensionFilter(){
            return extensionFilter;
        }
    }

    private static FileChooser instance = null;
    private static SimpleObjectProperty<File> lastKnownDirectoryProperty = new SimpleObjectProperty<>();

    private RetentionFileChooser(){ }

    private static FileChooser getInstance(FilterMode... filterModes){
        if(instance == null) {
            instance = new FileChooser();
            instance.initialDirectoryProperty().bindBidirectional(lastKnownDirectoryProperty);
        }
        //Set the filters to those provided
        //You could add check's to ensure that a default filter is included,adding it if need be
        instance.getExtensionFilters().setAll(
                Arrays.stream(filterModes)
                        .map(FilterMode::getExtensionFilter)
                        .collect(Collectors.toList()));
        return instance;
    }

    public static File showOpenDialog(FilterMode... filterModes){
        return showOpenDialog(null,filterModes);
    }

    public static File showOpenDialog(Window ownerWindow,FilterMode...filterModes){
        File chosenFile = getInstance(filterModes).showOpenDialog(ownerWindow);
        if(chosenFile != null){
            lastKnownDirectoryProperty.setValue(chosenFile.getParentFile());
        }
        return chosenFile;
    }

    public static File showSaveDialog(FilterMode... filterModes){
        return showSaveDialog(null,filterModes);
    }

    public static File showSaveDialog(Window ownerWindow,FilterMode... filterModes){
        File chosenFile = getInstance(filterModes).showSaveDialog(ownerWindow);
        if(chosenFile != null){
            lastKnownDirectoryProperty.setValue(chosenFile.getParentFile());
        }
        return chosenFile;
    }
}

用法示例:

//Note the previous example still holds
File chosenFile = RetentionFileChooser.showOpenDialog();
File file = RetentionFileChooser.showSaveDialog(FilterMode.PNG_FILES);

but this does not work if the dialog is closed or canceled.

遗憾的是,FileChooser在关闭/终止之前不会公开有关正在检查的目录的信息.如果您对类进​​行反编译并进行跟踪,则最终会触发本机调用.因此即使FileChooser不是最终允许它被子类化,它也不太可能获得这些信息

上述方法提供的唯一好处是,如果遇到此情况,它不会更改初始目录

如果你有兴趣,这个问题中的本地关键词有一些非常好的答案和链接:

> What is the native keyword in Java for?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Alt+回车 导入包,自动修正Ctrl+N 查找类Ctrl+Shift+N 查找文件Ctrlʺlt+L 格式化代码Ctrlʺlt+O 优化导入的类和包Alt+Insert 生成代码(如get,set方法,构造函数等)Ctrlʾ或者Alt+Shiftʼ 最近更改的代码Ctrl+R 替换文本Ct
运行程序出现下面错误:HTTP Status 500 ---------------------------------------------------------------------------------type Exception reportmessagedescription Th
1、建立DM的profile,使用的模版在install_root/profileTemplates/dmgr下句法为:manageprofile.sh -create -templatePath install_root/profileTemplates/dmgr调用参数为:-create 建立一
使用dom4j解析XML时,要快速获取某个节点的数据,使用XPath是个不错的方法,dom4j的快速手册里也建议使 用这种方式,标题都写的这么阔气:Powerful Navigation with XPath。 方法是使用Document的selectNodes(String XPath)方法,代码
英文操作系统导致 Debug 下的变量查看时显示乱码,可通过改变字体解决此问题。
eclipse中javascript报错问题处理:三个地方:&lt;1&gt;&quot;eclipse设置 &quot;:Java代码window-&gt;preference-&gt;Validator-&gt;Errors/Warnings-&gt;Enable Javascript Sema
打开eclipse中文字体很小,简直难以辨认。在网上搜索发现这是由于Eclipse 用的字体是 Consolas,显示中文的时候默认太小了。解决方式有两种:一、把字体设置为Courier New操作步骤:打开Elcipse,点击菜单栏上的“Windows”——点击“Preferences”——点击“
如果不加密码,默认只能本机访问,加密码也是为了安全考虑 1.进入Redis&#160;的安装目录,找到redis.conf文件。用vi命令打开文件 输入 / requirepass 进行查找,输入n查找下一个。 (最好复制一个新的conf文件) 在红背景处设置密码 2.重启 Redis &amp;
设置LINUX 自启动: 在/etc/rc.d/rc.local中加入: conf 目录下一个文件&#160;server.xml
ArrayList 和Vector是采用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,都允许直接序号索引元素,但是插入数据要设计到数组元素移动等内存操作,所以索引数据快插入数据慢,Vector由于使用了synchronized方法(线程安全)所以性能上比ArrayList要差,
在实现设计模式之前,首先来复习以下UML中的五种关系图 依赖&lt;关联&lt;聚合&lt;组合 &lt;1&gt;依赖 依赖关系用虚线加箭头表示,如图所示: 上图表示:Animal类依赖于Water类(动物依赖于水)。 依赖是类的五种关系中耦合最小的一种关系。因为依赖关系在生成代码的时候,这两个关
第一步:准备包:日志相关包jcl-over-slf4j-1.6.1.jarlogback-classic-0.9.29.jarlogback-core-0.9.29.jarslf4j-api-1.6.1.jarjstl包jstl-1.2.jarspring 相关包org.springframewor
当运行这个web程序时,无法运行,提示错误如下: 当时安装的tomcat是tomcat7版本,安装的jdk版本是1.6。 配置的tomcat如下:window-Preferences-Server-Runtime Environment,添加tomcat。如下: 检查多次,tomcat安装,环境配置
代码中 会让补全,否则会报&#160;diamond operator is not supported in -source 1.5 需要在POM中指定 source 版本号
原因:这是由于jdk的版本与项目的要求不一致造成的,如果是maven项目,首先查看一下pom.xml,以我的项目为例: 从其中可以看出要求的编译插件为1.8版本,而我本机上安装的jdk为1.7版本,因此需要首先下载安装1.8版本的jdk下载链接为 jdk下载链接 然后在intellij idea中点
照着教程弄的第一个 DEMO,结果启不来。 解决办法:在Controller 上面加上&#160;@EnableAutoConfiguration 成功启动 Demo的其它内容及配置如下图,新建一个 空的 Maven 项目 Pom.xml 主界面: Control.java 运行报错 :: Spri
如下图所示,我的是 2018,不同版本,Schema 可能要 Save As一下
Ant Design Pro Vue 打包发布到Tomcat后,刷新报错404解决方法 在应用下面加 WEB-INF&#160;建&#160;web.xml&#160;内容如下 &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&qu
效果如图: JAVA&#160;代码 public static void main(String[] args) throws Exception { String str = &quot;&lt;row PTID=\&quot;80268175\&quot; ZYH=\&quot;2002868
HTTP Status 500 - Handler processing failed; nested exception is java.lang.AbstractMethodError: org.apache.xerces.dom.ElementNSImpl.setUserData(Ljava/