如何使用JFileChooser.showOpenDialog打开特定文件?

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