How to make JFileChooser Default to Computer View instead of My Documents
Asked Answered
P

3

7

In the Windows Look and Feel for JFileChooser, the left hand side of the JFileChooser dialog shows five buttons: Recent Items, Desktop, My Documents, Computer, and Network. These each represent Views of the file system as Windows Explorer would show them. It appears that JFileChooser defaults to the My Documents View unless the setSelectedFile() or setCurrentDirectory() methods are called.

I am attempting to make it easy for the user to select one of a number of mapped network drives, which should appear in the "Computer" View. Is there a way to set the JFileChooser to open the "Computer" view by default?

I have tried a couple methods to force it, the most recent being to find the root directory and set it as the currentDirectory, but this shows the contents of that root node. The most recent code is included below.

private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            JFileChooser origDriveChooser = new JFileChooser();
            origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            File startFile = new File(System.getProperty("user.dir")); //Get the current directory

            // Find System Root
            while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
            {
                startFile = startFile.getParentFile();
            }

            origDriveChooser.setCurrentDirectory(startFile);
            origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
            int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
            if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
            {
                originalUnitServerRoot = origDriveChooser.getSelectedFile();

            }
        }
    }

Is there a method that allows me to select the "Computer" view by default (or the Network, or any other view), or any way to trick the JFileChooser?

EDIT
Thanks for the quick and thorough answers. I combined Hovercraft Full Of Eels' and Guillaume Polet's answers to try and make the code work on any drive letter. The resulting code is as follows. Once again, thanks.

private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            JFileChooser origDriveChooser = new JFileChooser();
            origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            File startFile = new File(System.getProperty("user.dir")); //Get the current directory

            // Find System Root
            while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
            {
                startFile = startFile.getParentFile();
            }
            //Changed the next line
            origDriveChooser.setCurrentDirectory(origDriveChooser.getFileSystemView().getParentDirectory(rootFile));
            origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
            int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
            if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
            {
                originalUnitServerRoot = origDriveChooser.getSelectedFile();

            }
        }
    }
Plutus answered 9/5, 2012 at 21:31 Comment(0)
B
6

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);
    }
}
Beggary answered 9/5, 2012 at 22:1 Comment(0)
A
4

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);
        }
     }
  }
Ariannaarianne answered 9/5, 2012 at 21:57 Comment(4)
I just found out that FileSystemView has a isComputerNode(File) method which would be cleaner than comparing Strings.Beggary
@GuillaumePolet: I tried using that, but it didn't work: if (defaultFile != null && fsv.isComputerNode(defaultFile)) {Ariannaarianne
You are right, I just tested and it returns false. And I just looked at the JavaDoc: Returns: false alwaysBeggary
@HovercraftFullOfEels I tried that as well, and I ended up with a null pointer exception. (Looks like it ran out of parent directories before it encountered a ComputerNode.) I just used the rootNode and used FileSystemViewer to getParentDirectory() once more. That seemed to do the trick.Plutus
B
0
//Specify the absolute path of the Mapped Drive

chooser.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"));
Bachman answered 26/9, 2014 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.