Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Setting a specified start folder for JFileChooser setCurrentDirectory()

Posted on 2014-12-07
7
732 Views
Last Modified: 2014-12-08
I am trying to set a specific working folder for JFileChooser as specified in a String PROJECT_FOLDER + "\\PCBs" for base folder for opening files in this directory, where PROJECT_FOLDER is a final String containing a project directory absolute path in Windows, such as: .

The method below will have a parameter of the file extension as a String, because only a certain type of files
should show up in the JFileChooser interface if that certain type of files is to be opened by the user, determined
by the parameter passed down to the method.

The method should return the absolute path to the file that the user chose to open.

I just don't know how to point  JFileChooser to the specific folder defined in a String upon startup of the open
dialog box of  JFileChooser, instead of browsing to the folder from the default folder:

                   jfc.setCurrentDirectory(f);     // This works, but you have to browse through folders !

                   jfc.setCurrentDirectory(PROJECT_FOLDER + "\\PCBs");    // This doesn't work!

                   
// The userFileNameFromUser() method will acquire the filename of the file to be opened
// from the user and return the file name and file path as a String:

            public String getFileNameFromUser(String extensionString) {

                String fileNameAndPath = "";

                JFileChooser jfc = new JFileChooser();
                try {
                    File f = new File(new File(".").getCanonicalPath());
                   // jfc.setCurrentDirectory(f);
                   jfc.setCurrentDirectory(PROJECT_FOLDER + "\\PCBs");    // This doesn't work!

                } catch (IOException except) {
                    System.out.println("Unable to set current directory!");
                  
                    JOptionPane.showMessageDialog(null, "Unable to set current directory.", "Loading Data",
                                                  JOptionPane.ERROR_MESSAGE);
                }


                switch (extensionString) {
                case ".pcb":
                    jfc.setFileFilter(new PCBFileFilter());
                    break;
                case ".cap":
                    jfc.setFileFilter(new DiagFileFilter());
                    break;
                case ".csv":
                        jfc.setFileFilter(new CSVFileFilter());
                        break;
                case ".asc":
                            jfc.setFileFilter(new ASCFileFilter());
                            break;
                
                }

                int result = jfc.showOpenDialog(null);

                if (result == JFileChooser.CANCEL_OPTION) {
                
                    JOptionPane.showMessageDialog(null, "No file was chosen.", "File not loaded", JOptionPane.WARNING_MESSAGE);
                    return fileNameAndPath; 
                }

                try {
                    File file = jfc.getSelectedFile();
                    fileNameAndPath = file.getPath();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Failure to open file.", "Loading Data", JOptionPane.ERROR_MESSAGE);
                   
                }
                // Do not process further if wrong file extension:
                if (!(fileNameAndPath.toLowerCase().endsWith(extensionString))) {
                    
                    JOptionPane.showMessageDialog(null, "PCB file type required.", "Incorrect Data", JOptionPane.ERROR_MESSAGE);
                }
                return fileNameAndPath;
            }

Open in new window


PCBFileFilter, DiagFileFilter, CSVFileFilter, etc. are inner classes extending javax.swing.filechooser.FileFilter

Thanks for your help.
0
Comment
Question by:AttilaB
  • 3
  • 2
  • 2
7 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 40485545
I think you have to set the FileSystemView in the FileChooser constructor, to pick its default directory view. Take a look at the API.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40485554
Try
jfc.setCurrentDirectory(new File(PROJECT_FOLDER, "PCBs"));

Open in new window

0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40485627
This comment is not in any shape intended to dis CEHJ's comment - which is most likely correct. But as I'd already made mine, it falls to me to say that in this : (which I've now edited)

JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView());
		 System.out.println(jfc.getCurrentDirectory().toString());

Open in new window


. . . you'd see your OS-defined user current dir. So you might want to think about extra-Java setting of that directory . . . if that would be appropriate for you.

Course you can see the default dir with :
System.out.println(FileSystemView.getFileSystemView().getDefaultDirectory().toString());

Open in new window

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:AttilaB
ID: 40485932
I tried:

jfc.setCurrentDirectory(new File(PROJECT_FOLDER, "PCBs"));

Open in new window


It will actually take me to the system default folder ("C:\\Users\\Attila\Documents") , instead of the  PROJECT_FOLDER + "\\PCBs" where I wanted to go.

So, if we tried to hard-code - just to make it simple - where I wanted the opening JFileChooser Open dialog box to take me to browse files by default is:

"C:\\goepel\\CAS4WIN\\Uuts\\00061055G 55-75100 CPLD DB Shorted\\CAD\\PCBs"

OK. If I run:

JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView());
		 System.out.println(jfc.getCurrentDirectory().toString());

Open in new window


What I get is:      C:\Users\Attila\Documents  printed.

So we have no trouble finding or understanding that our default directory is this.

Krakatoa said:

  "So you might want to think about extra-Java setting of that directory . . ."

I don't understand what this sentence refers to.

Also, can you elaborate what exactly this means too:

"I think you have to set the FileSystemView in the FileChooser constructor, to pick its default directory view. Take a look at the API"

So, where I need to get is here:

"C:\\goepel\\CAS4WIN\\Uuts\\00061055G 55-75100 CPLD DB Shorted\\CAD\\PCBs"

which is a directory name defined by a String, so I don't understand how finding the system default directory will
help me in this case.

Thanks for looking at this.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 40485974
Works for me - no reason to think it will fail on other OSs:

import java.awt.*;
import java.awt.event.*;

import java.io.*;

import java.util.*;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;


public class FB extends JFrame implements ActionListener {
    private final static String PROJECT_FOLDER = "/tmp/goepel/CAS4WIN/Uuts/00061055G 55-75100 CPLD DB Shorted/CAD";
    private JButton b;

    // The userFileNameFromUser() method will acquire the filename of the file to be opened
    // from the user and return the file name and file path as a String:
    public String getFileNameFromUser(String extensionString) {
        String fileNameAndPath = "";

        JFileChooser jfc = new JFileChooser();

        try {
            // Temporary code kludge - no method here DOES throw an Exception
            jfc.setCurrentDirectory(new File(PROJECT_FOLDER, "PCBs"));
        } catch (Exception except) {
            System.out.println("Unable to set current directory!");

            JOptionPane.showMessageDialog(null,
                "Unable to set current directory.", "Loading Data",
                JOptionPane.ERROR_MESSAGE);
        }

        switch (extensionString) {
        case ".pcb":
            jfc.setFileFilter(new PCBFileFilter());

            break;

            /*
            case ".cap":
            jfc.setFileFilter(new DiagFileFilter());

            break;

            case ".csv":
            jfc.setFileFilter(new CSVFileFilter());

            break;

            case ".asc":
            jfc.setFileFilter(new ASCFileFilter());

            break;
            */
        }

        int result = jfc.showOpenDialog(null);

        if (result == JFileChooser.CANCEL_OPTION) {
            JOptionPane.showMessageDialog(null, "No file was chosen.",
                "File not loaded", JOptionPane.WARNING_MESSAGE);

            return fileNameAndPath;
        }

        try {
            File file = jfc.getSelectedFile();
            fileNameAndPath = file.getPath();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Failure to open file.",
                "Loading Data", JOptionPane.ERROR_MESSAGE);
        }

        // Do not process further if wrong file extension:
        if (!(fileNameAndPath.toLowerCase().endsWith(extensionString))) {
            JOptionPane.showMessageDialog(null, "PCB file type required.",
                "Incorrect Data", JOptionPane.ERROR_MESSAGE);
        }

        return fileNameAndPath;
    }

    public void actionPerformed(java.awt.event.ActionEvent e) {
        getFileNameFromUser(".pcb");
    }

    private void setGui() {
        try {
            setLocation(0, 100);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            Container cp = getContentPane();
            JPanel bPanel = new JPanel();
            b = new JButton("Click");
            b.addActionListener(this);
            bPanel.add(b);
            cp.add(bPanel, BorderLayout.SOUTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        FB f = new FB();
                        f.setGui();
                        f.setSize(200, 200);
                        f.setVisible(true);
                    }
                });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class PCBFileFilter extends FileFilter {
        @Override
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".pcb");
        }

        @Override
        public String getDescription() {
            return "";
        }
    }
}

Open in new window


Shot
0
 

Author Comment

by:AttilaB
ID: 40486058
You are right, it does work as you said!

jfc.setCurrentDirectory(new File(PROJECT_FOLDER + "\\CAD\\PCBs"));

I left the CAD out, so it pointed to a non-existent folder. Otherwise fine.

Interesting, that if the folder doesn't exist instead of creating an exception it just goes to the default folder. This is what through me off.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40486487
Hmm, I must be missing something because even with the directory in place, this impl still points at the OS user dir, not the project folder.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

791 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question