Java JFileChooser with Filter to supposedly display ONLY directories fail to show just directories

徘徊边缘 提交于 2019-12-08 19:23:35

问题


(Thanks in advance! Please let me know if you need more info. Sample code at the bottom.)

Problem I'm trying to solve:

I'm trying to get this JFileChooser object to display only directories (and not files), through the use of a javax.swing.filechooser.FileFilter object that has this in the accept(File file) overridden method: return file.isDirectory();. However, at least on my mac, it doesn't seem to prevent files from being displayed along with the directories (it does prevent files from being selected without using the setFileSelectionMode() method).

Question

Am I missing something? If not, has anyone ever encountered this before?

My understanding/assumptions:

  1. The magic should happen when you pass in a javax.swing.filechooser.FileFilter object into the JFileChooser's setFileFilter() method.
  2. Seems like my JFileChooser with setFileFilter() is behaving like its using of setSelectionMode( JFileChooser.DIRECTORIES_ONLY );

Code

import java.io.File;
import javax.swing.filechooser.FileFilter;

// inside a method that's adding this to a JPanel

_fileChooser = new JFileChooser( "." );
_fileChooser.setControlButtonsAreShown( false );
_fileChooser.setFileFilter( new FolderFilter() );
// _fileChooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
_panelMidLeft.add( _fileChooser );

// an inner class, defined somewhere else in the class

private class FolderFilter extends javax.swing.filechooser.FileFilter {
  @Override
  public boolean accept( File file ) {
    return file.isDirectory();
  }

  @Override
  public String getDescription() {
    return "We only take directories";
  }
}

Thanks!

Alex


回答1:


Your code works for me. My SSCCE:

import java.io.File;
import javax.swing.JFileChooser;

public class ShowDirectoriesOnly {
   public static void main(String[] args) {
      JFileChooser fileChooser = new JFileChooser( "." );
      fileChooser.setControlButtonsAreShown( false );
      fileChooser.setFileFilter( new FolderFilter() );
      fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      fileChooser.showOpenDialog(null);
   }

   private static class FolderFilter extends javax.swing.filechooser.FileFilter {
      @Override
      public boolean accept( File file ) {
        return file.isDirectory();
      }

      @Override
      public String getDescription() {
        return "We only take directories";
      }
    }
}

If you're still having problems, your best is to create your own SSCCE that demonstrates your problem.

Edit

Screenshot on how it looks under OS X with JDK1.7



来源:https://stackoverflow.com/questions/10055910/java-jfilechooser-with-filter-to-supposedly-display-only-directories-fail-to-sho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!