How to make JFileChooser Default to Computer View instead of My Documents How to make JFileChooser Default to Computer View instead of My Documents windows windows

How to make JFileChooser Default to Computer View instead of My Documents


Here is a working example. It makes the assumption that C:\ is a valid path. It uses the FileSystemView.getParentDir(File)

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.SwingUtilities;public class Test {    /**     * @param args     */    public static void main(String[] args) {        SwingUtilities.invokeLater(new Runnable() {            @Override            public void run() {                new Test().initUI();            }        });    }    protected void initUI() {        JFrame frame = new JFrame();        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        JPanel panel = new JPanel();        final JButton button = new JButton("Select files...");        button.addActionListener(new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                final JFileChooser chooser = new JFileChooser();                chooser.setCurrentDirectory(                                 chooser.getFileSystemView().getParentDirectory(                                     new File("C:\\")));                              chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);                chooser.showDialog(button, "Select file");            }        });        panel.add(button);        frame.add(panel);        frame.pack();        frame.setLocationRelativeTo(null);        frame.setVisible(true);    }}


A kludge way to do this is to get the default directory's parent until the toString() of the File obtained is "Computer". something like:

  FileSystemView fsv = FileSystemView.getFileSystemView();  File defaultFile = fsv.getDefaultDirectory();  while (defaultFile != null) {     defaultFile = defaultFile.getParentFile();     if (defaultFile != null && "Computer".equalsIgnoreCase(defaultFile.toString())) {        JFileChooser fileChooser = new JFileChooser(defaultFile);        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);        int result = fileChooser.showOpenDialog(null);        if (result == JFileChooser.APPROVE_OPTION) {           File file = fileChooser.getSelectedFile();           System.out.println(file);        }     }  }


//Specify the absolute path of the Mapped Drivechooser.setCurrentDirectory(new File("B:\\exampleFolder"));

OR

// set the file opener to look at the desktop    JFileChooser chooser = new JFileChooser();        chooser.setCurrentDirectory(new File(System.getProperty("user.home") + "\\Desktop"));