Solved

Setting a specified start folder for JFileChooser setCurrentDirectory()

Posted on 2014-12-07
7
616 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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

705 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now