Andreas Neophytou
Andreas Neophytou

Reputation: 151

Java: Force JFileChooser to one directory and it's sub-folders

I have created a JFileChooser and I want to restrict it only in the user.home dir and it's subfolders.

The selection mode of my JFileChooser is directories only.

So far I have used this:

//JButton select = new JButton();
final File directorylock = new File(System.getProperty("user.home"));
JFileChooser browse = new JFileChooser(directorylock);
browse.setFileView(new FileView() {
    @Override
    public Boolean isTraversable(File f) {
         return directorylock.equals(f);
    }
});

But every time I open the JFileChooser it only shows me the user.home directory without it's subfolders and therefore I cannot access them or select them.

How it should work: Open JFileChooser and show the user.home directory with all it's subfolders. Be able to access the subfolders and select them. NOT be able to access parent folders. of the user.home directory.

I hope someone here knows how this is supposed to be done! :) Thank you guys in advance :D

Upvotes: 4

Views: 1729

Answers (3)

camickr
camickr

Reputation: 324118

Check out the Single Root File Chooser.

You will only ever see the single file you specify in the combo box so you don't confuse the user that you can select a parent directory.

Then You will only be able to select a file in the directory or sub directory of the file you specify when creating the class.

Upvotes: 3

RubioRic
RubioRic

Reputation: 2468

With a little modification, I think that Vishal Gajera's solution may work. I've copied a method from Check if file is in (sub)directory give by tsauerwein

   /**
    * Checks, whether the child directory is a subdirectory of the base 
    * directory.
    *
    * @param base the base directory.
    * @param child the suspected child directory.
    * @return true, if the child is a subdirectory of the base directory.
    * @throws IOException if an IOError occured during the test.
    */
   public boolean isSubDirectory(File base, File child) {

       boolean res = false;

       try {
        base = base.getCanonicalFile();
           child = child.getCanonicalFile();

           File parentFile = child;
           while (!res && parentFile != null) {
               if (base.equals(parentFile)) {
                   res = true;
               }
               parentFile = parentFile.getParentFile();
           }
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }

       return res;
   }


 private void showFileChooserDemo(){
      headerLabel.setText("Control in action: JFileChooser"); 

      final File directorylock = new File(System.getProperty("user.home"));
      final JFileChooser  fileDialog = new JFileChooser(directorylock);

      fileDialog.setFileView(new FileView() {
            @Override
            public Boolean isTraversable(File f) {
                 return isSubDirectory(directorylock, f);
            }
        });

      JButton showFileDialogButton = new JButton("Open File");
      showFileDialogButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            int returnVal = fileDialog.showOpenDialog(mainFrame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
               java.io.File file = fileDialog.getSelectedFile();
               statusLabel.setText("File Selected :" 
               + file.getName());
            }
            else{
               statusLabel.setText("Open command cancelled by user." );           
            }      
         }
      });
      controlPanel.add(showFileDialogButton);
      mainFrame.setVisible(true);  
   }

Upvotes: 2

Vishal Gajera
Vishal Gajera

Reputation: 4207

Please refer this Sample, it's works fine as like you want,

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileView;

public class JFileChooserExample {

       private JFrame mainFrame;
       private JLabel headerLabel;
       private JLabel statusLabel;
       private JPanel controlPanel;

       public JFileChooserExample(){
          prepareGUI();
       }

       public static void main(String[] args){
           JFileChooserExample  swingControlDemo = new JFileChooserExample();      
          swingControlDemo.showFileChooserDemo();
       }

       private void prepareGUI(){
          mainFrame = new JFrame("Java Swing Examples");
          mainFrame.setSize(400,400);
          mainFrame.setLayout(new GridLayout(3, 1));
          mainFrame.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent windowEvent){
                System.exit(0);
             }        
          });    
          headerLabel = new JLabel("", JLabel.CENTER);        
          statusLabel = new JLabel("",JLabel.CENTER);    

          statusLabel.setSize(350,100);

          controlPanel = new JPanel();
          controlPanel.setLayout(new FlowLayout());

          mainFrame.add(headerLabel);
          mainFrame.add(controlPanel);
          mainFrame.add(statusLabel);
          mainFrame.setVisible(true);  
       }

       private void showFileChooserDemo(){
          headerLabel.setText("Control in action: JFileChooser"); 

          final File directorylock = new File(System.getProperty("user.home"));
          final JFileChooser  fileDialog = new JFileChooser(directorylock);

          fileDialog.setFileView(new FileView() {
                @Override
                public Boolean isTraversable(File f) {
                     return directorylock.equals(f);
                }
            });

          JButton showFileDialogButton = new JButton("Open File");
          showFileDialogButton.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
                int returnVal = fileDialog.showOpenDialog(mainFrame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                   java.io.File file = fileDialog.getSelectedFile();
                   statusLabel.setText("File Selected :" 
                   + file.getName());
                }
                else{
                   statusLabel.setText("Open command cancelled by user." );           
                }      
             }
          });
          controlPanel.add(showFileDialogButton);
          mainFrame.setVisible(true);  
       }
    }

Out-Put :

enter image description here

Upvotes: 2

Related Questions