Solved

Setting a specified start folder for JFileChooser setCurrentDirectory()

Posted on 2014-12-07
7
658 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
network + 7 80
split53 challenge 7 77
topping1 challenge 7 72
VB Script to add site to Java Exception List 4 48
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
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.

932 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

11 Experts available now in Live!

Get 1:1 Help Now