![](/img/trans.png)
[英]How to use JFileChooser.showOpenDialog() in a non component class?
[英]How to use JFileChooser.showOpenDialog to open a specific file?
現在我可以打開我想要的任何文件,但是打開的默認文件是我的文檔。 如何設置保存在我的 java 項目中的文件的默認路徑?
現在這就是我所擁有的:
try{
int option = chooser.showOpenDialog(MyPanel.this);//Chooser is my JFileChooser
if(option == JFileChooser.APPROVE_OPTION) {
//do stuff
}
}catch(Exception ex){}
如果文件夾位於我的 java 項目中,我必須向showOptionDialog()
傳遞什么才能打開它?
你可以用像
JFileChooser chooser = new JFileChooser("desired_current_directory");
要么
chooser.setCurrentDirectory(new File("desired_current_directory"));
如果要在項目目錄下打開“ My Pics
文件夾,請使用
JFileChooser chooser = new JFileChooser("./My Pics");
您可以像這樣將目錄添加到JFileChooser的構造函數中:
JFileChooser fileChooser = new JFileChooser("directory");
或者您可以使用setCurrentDirectory(File dir)
設置當前目錄:
fileChooser.setCurrentDirectory(new File("directory"));
僅使用構造函數進行設置可能會更容易,但是如果在創建JFileChooser之后需要更改它,請使用setCurrentDirectory(File dir)
。
您可以像這樣將目錄添加到 JFileChooser 的構造函數中:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("put here your directory"));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
jTextField.setText(selectedFile.getAbsolutePath());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.