【问题标题】:How to set the last path as the next default using JFileChooser如何使用 JFileChooser 将最后一个路径设置为下一个默认值
【发布时间】:2014-04-23 13:55:26
【问题描述】:

我有几个提供文件选择器的对话框。首先,我的编码是这样的

JFileChooser chooser= new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal= chooser.showOpenDialog(this);

        if(returnVal==JFileChooser.APPROVE_OPTION){
            File f= chooser.getSelectedFile();
            jTextField1.setText(f.getPath());
            chooser.setCurrentDirectory(f);
        }

在我的情况下,我想在下一个选择 JFileChooser 中将最后一个路径设置为默认路径。有什么解决办法吗? 感谢您的任何回复

【问题讨论】:

  • 我认为您必须在关闭程序之前将“当前”路径写入文件。然后下一次,从文件中读取路径并使用它。这只是一种方法,许多人可能会说它错了.. :)
  • chooser.setSelectedFile 会将“当前选定的文件”设置为您提供的任何File。但是正如 WhoAmI 所暗示的,保存之前选择的文件是您必须自己处理的事情。我不认为 JFileChooser 会为你这样做,除非我错过了什么。
  • 您是否希望在关闭应用程序并重新启动后保留此默认路径?
  • @WhoAmI :我阅读了一些尝试setCurrentDirectory() 的建议,但我还没有这样做。 @ajb : 如果JFileChooser 不是正确的方式,那么我必须采取什么样的方式? @Jbueno:是的。你对我有什么建议吗?谢谢
  • @syaloom - MadProgrammer 为你展示了它..

标签: java path directory jfilechooser


【解决方案1】:

根据您的要求,您可以使用 Preferences 将其存储起来,并在程序重新启动后再次使用。

 Preferences pref = Preferences.userRoot();

// Retrieve the selected path or use
// an empty string if no path has
// previously been selected
String path = pref.get("DEFAULT_PATH", "");

JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

// Set the path that was saved in preferences
chooser.setCurrentDirectory(new File(path));

int returnVal = chooser.showOpenDialog(null);

if (returnVal == JFileChooser.APPROVE_OPTION)
{
    File f = chooser.getSelectedFile();
    chooser.setCurrentDirectory(f);

    // Save the selected path
    pref.put("DEFAULT_PATH", f.getAbsolutePath());
}

【讨论】:

    【解决方案2】:

    你必须“记住”最后一条路径。

    这可以通过将值存储在实例变量中来轻松完成...

    private File lastPath;
    //...
    lastPath = f.getParentFile();
    

    当您需要时,只需重置它...

    //...
    if (lastPath != null) {
        chooser.setCurrentDirectory(lastPath);
    }
    

    您也可以使用JFileChooser 的单个实例,因此每次显示它时,它都会位于上次使用的位置...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多