Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFileChooser select directory but show files

I feel like there should be a simple way to do this but I can't figure it out. I have a JFileChooser that allows the user to select directories. I want to show all the files in the directories to give the user some context, but only directories should be accepted as selections (maybe the Open button would be disabled when a file is selected). Is there an easy way of doing this?

like image 477
Jeff Storey Avatar asked May 21 '10 15:05

Jeff Storey


People also ask

How do I get files from JFileChooser?

JFileChooser has a method, getSelectedFile(). Which is a File. If you open the dialog with showSaveDialog() you should be able to get the File from that (file. getName()).

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.


1 Answers

My solution is a merge between the answers of camickr and trashgod:

    final JFileChooser chooser = new JFileChooser() {
            public void approveSelection() {
                if (getSelectedFile().isFile()) {
                    return;
                } else
                    super.approveSelection();
            }
    };
    chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
like image 95
ablaeul Avatar answered Sep 18 '22 23:09

ablaeul