![](/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.