JFileChooser and eclipse
Asked Answered
T

3

0

I am looking for a way to have JFileChooser allow the user to choose from txt files that are included in the bin file of eclipse project only. Is there a way to have the JFileChooser pop up and display a selected number of txt files that reside with in the bin folder?

Tintinnabulum answered 6/12, 2012 at 12:25 Comment(5)
are you running the app from Eclipse, jar or both?Podagra
Will the user run your application from Eclipse? If not, your question is pointless.Gillies
@GuillaumePolet, I agree. Relative path makes sense for running from Eclipse only. Otherwise, you need to use absolute path, but then what you are trying to do is non-understandable.Podagra
Yes they will run the demo from eclipseTintinnabulum
It should be straightforward to do this. For instance, you can give a file reader object a string with the txt file name and eclipse is able to find it. So now I just want to find a way to make a directory that points at the bind folder and just picks up txt filesTintinnabulum
P
3

You can refer to the following code, just specify absolute or relative path to your folder/dir

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "TXT files", "txt");
chooser.setFileFilter(filter);
chooser.setCurrentDirectory("<YOUR DIR COMES HERE>");
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

JFileChooser

Podagra answered 6/12, 2012 at 12:29 Comment(3)
@Nicolay Kuznetsov Hi..Thanks for that ..but is there a way to point only at txt files that reside in the eclipse bin folder of a given project??Tintinnabulum
Thanks but the bit I am trying to work out is how to set the relative path so that different people using the app will only have the txt files I have set to choose fromTintinnabulum
I don't understand why people from the app need to see the list of txt-files in unrelated eclipse project. Please, update the question with Eclipse project structure and how you run the app. If you run it from JAR then it have to be absolute path.Podagra
E
2

So you only want to display certain text files in the directory?

Use a FileFilter which will check the files name against an ArrayList of file names if a match is found it will return true which will allow JFileChooser to show file

Something like:

JFileChooser fc=..;
fc.setCurrentDirectory(new File("path/to/bin/"));//put path to bin here

 ....     

 ArrayList<String> filesToSee=new ArrayList<>();
 //add names of files we want to be visible to user of JFileChooser
 filesToSee.add("file1.txt");
 filesToSee.add("file2.txt");

fc.addChoosableFileFilter(new MyFileFilter(filesToSee));

//By default, the list of user-choosable filters includes the Accept All filter, which        enables the user to see all non-hidden files. This example uses the following code to disable the Accept All filter:
fc.setAcceptAllFileFilterUsed(false);

....

class MyFileFilter extends FileFilter {

     private ArrayList<String> files;

     public MyFileFilter(ArrayList<String> files) {
         this.files=files;
     }

    //Accept only files in passed array
    public boolean accept(File f) {

        for(String s:files) {
            if(f.getName().equals(s)) {
                return true;
             }
        }

        return false;
    }

    //The description of this filter
    public String getDescription() {
        return "Specific Files";
    }
}

Reference:

Elston answered 6/12, 2012 at 13:13 Comment(0)
G
2

Another way to do it is to implement the FileSystemView so that it only shows your directory and prevent from going upper in the hierarchy or other "drives".

Here is a demo of such a FileSystemView. All you have to provide in input is the root directory (ie, the path to your bin, probably something such as new File("bin") if the working dir is considered to be the root of your Eclipse project which is what Eclipse does by default).

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;

public class TestJFileChooser2 {

    public static class MyFileSystemView extends FileSystemView {

        private File root;

        public MyFileSystemView(File root) {
            super();
            try {
                this.root = root.getCanonicalFile();
            } catch (IOException e) {
                this.root = root;
            }
        }

        @Override
        public File[] getRoots() {
            return new File[] { root };
        }

        @Override
        public File createNewFolder(File containingDir) throws IOException {
            return FileSystemView.getFileSystemView().createNewFolder(containingDir);
        }

        @Override
        public File createFileObject(String path) {
            File file = super.createFileObject(path);
            if (isEmbedded(file)) {
                return file;
            } else {
                return root;
            }
        }

        @Override
        public File createFileObject(File dir, String filename) {
            if (isEmbedded(dir)) {
                return super.createFileObject(dir, filename);
            } else {
                return root;
            }

        }

        @Override
        public File getDefaultDirectory() {
            return root;
        }

        private boolean isEmbedded(File file) {
            while (file != null && !file.equals(root)) {
                file = file.getParentFile();
            }
            return file != null;
        }

        @Override
        public File getParentDirectory(File dir) {
            File parent = dir.getParentFile();
            if (isEmbedded(parent)) {
                return parent;
            } else {
                return root;
            }
        }
    }

    protected void initUI() {
        JFrame frame = new JFrame("Test file chooser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JButton ok = new JButton("Click me to select file");
        ok.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        final JFileChooser openFC = new JFileChooser(new MyFileSystemView(new File("")));
                        openFC.setDialogType(JFileChooser.OPEN_DIALOG);
                        // Configure some more here
                        openFC.showDialog(ok, null);
                    }
                });
            }
        });
        frame.add(ok);
        frame.setBounds(100, 100, 300, 200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {

                new TestJFileChooser2().initUI();
            }
        });
    }
}
Gillies answered 6/12, 2012 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.