Solved

Setting a specified start folder for JFileChooser setCurrentDirectory()

Posted on 2014-12-07
7
699 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

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

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
groupSumClump challenge 9 115
jar file executable 12 52
Groovy problem when using SOAPUI : DispatchException occurred 7 45
eclipse console opening separately 2 21
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
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 …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

777 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