简体   繁体   English

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

[英]How to use JFileChooser.showOpenDialog to open a specific file?

Right now I am able to open a up any file that I want, however the default file that opens up is My Documents.现在我可以打开我想要的任何文件,但是打开的默认文件是我的文档。 How can I set the default path to a file that is saved in my java project?如何设置保存在我的 java 项目中的文件的默认路径?

Right now this is what I have:现在这就是我所拥有的:

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

What do I have to pass into showOptionDialog() to open a folder if it is located in my java project ?如果文件夹位于我的 java 项目中,我必须向showOptionDialog()传递什么才能打开它?

You can use like 你可以用像

JFileChooser chooser = new JFileChooser("desired_current_directory");

or 要么

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

If you want to open My Pics folder under your project directory use 如果要在项目目录下打开“ My Pics文件夹,请使用

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

You can either add directory to the constructor of JFileChooser like this: 您可以像这样将目录添加到JFileChooser的构造函数中:

JFileChooser fileChooser = new JFileChooser("directory");

or you can set the current directory using setCurrentDirectory(File dir) : 或者您可以使用setCurrentDirectory(File dir)设置当前目录:

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

It is probably easier to just set it with the constructor, but if you need to change it after creating the JFileChooser, use setCurrentDirectory(File dir) . 仅使用构造函数进行设置可能会更容易,但是如果在创建JFileChooser之后需要更改它,请使用setCurrentDirectory(File dir)

You can either add directory to the constructor of JFileChooser like this:您可以像这样将目录添加到 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM