2011-10-05 47 views
1

我想記住用戶第一次輸入的目錄,然後將默認目錄設置爲先前選擇的目錄。我想通過存儲靜態變量路徑要做到這一點,並把它傳遞給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; 
    } 
} 

回答

4

嘗試fileopen.getCurrentDirectory(),而不是file.getPath()。或者只是讓你的文件選擇器作爲類字段:

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(); 
    } 
} 
+3

+1爲OR。這是最簡單的解決方案。 –

+0

@Eng。 Fouad,我無法爲fileopen.getCurrentDirectory返回String。 –