更改JFileChooser的目录

时间:2011-10-05 05:42:39

标签: java file swing path jfilechooser

我想记住用户第一次输入的目录,然后将默认目录设置为先前选择的目录。我试图通过将静态变量存储为路径并将其传递给JFileChooser来实现此目的,但是它无法正常工作,请告诉我原因,请:

 public class BrowseInputUI {
 public static String Path="";
 public BrowseInputUI() {
 JFileChooser fileopen = new JFileChooser(Path);//on second time user should see previous path
        int ret = fileopen.showDialog(null, "Provide a file");
        if (ret == JFileChooser.APPROVE_OPTION) {
          File file = fileopen.getSelectedFile();
                     Path=file.getPath();
         }
        else if (ret == JFileChooser.CANCEL_OPTION){
              Path=null;
        }
  }

  public String GetPath(){
         return Path;
     }
 }

1 个答案:

答案 0 :(得分:4)

尝试使用fileopen.getCurrentDirectory()代替file.getPath()。或者只是将您的filechooser作为类字段:

public class BrowseInputUI
{
    private JFileChooser fileopen = new JFileChooser();
    public BrowseInputUI()
    {
        int ret = fileopen.showDialog(null, "Provide a file");
        if(ret == JFileChooser.APPROVE_OPTION) File file = fileopen.getSelectedFile();
    }

    public String getPath()
    {
        return fileopen.getCurrentDirectory();
    }
}