2015-09-22 21 views
1

現在我可以打開任何我想要的文件,但打開的默認文件是「我的文檔」。我如何設置保存在我的Java項目中的文件的默認路徑?如何使用JFileChooser.showOpenDialog打開特定文件?

現在這就是我:

   try{ 
        int option = chooser.showOpenDialog(MyPanel.this);//Chooser is my JFileChooser 
        if(option == JFileChooser.APPROVE_OPTION) { 
         //do stuff 
        } 
       }catch(Exception ex){} 

我有什麼要傳遞到showOptionDialog()打開一個文件夾,如果它位於我的Java項目

+1

[JFileChooser在Windows中更改默認目錄]的可能重複(http://stackoverflow.com/questions/13516829/jfilechooser-change-default-directory-in-windows) –

回答

2

您可以像使用

JFileChooser chooser = new JFileChooser("desired_current_directory"); 

chooser.setCurrentDirectory(new File("desired_current_directory")); 

如果你想打開你的工程目錄下My Pics文件夾使用

JFileChooser chooser = new JFileChooser("./My Pics"); 
+0

很酷的工作!謝謝!是否有另一種方式來讀取該文件而不提供完整的路徑名?我問這個問題的原因是因爲如果我把這個項目交給某人並讓它在計算機上運行,​​那麼他們的路徑就不一樣了。我怎樣才能讓它從文件夾中讀取,如果它保存在我的Java項目中,可以說名爲「我的照片」? –

+0

編輯的答案,試試。 – ashiquzzaman33

2

您可以添加目錄構造JFileChooser是這樣的:

JFileChooser fileChooser = new JFileChooser("directory"); 

,或者您可以使用當前目錄setCurrentDirectory(File dir)設置:

fileChooser.setCurrentDirectory(new File("directory")); 

這可能是更容易只是用構造函數設置它,但如果你需要創建JFileChooser中後改變它,使用setCurrentDirectory(File dir)