简体   繁体   中英

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?

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 ?

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

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

You can either add directory to the constructor of JFileChooser like this:

JFileChooser fileChooser = new JFileChooser("directory");

or you can set the current directory using 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) .

You can either add directory to the constructor of JFileChooser like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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