java 在指定目录启动 JFileChooser 并仅显示特定类型的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15954770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:25:36  来源:igfitidea点击:

Starting a JFileChooser at a specified directory and only showing files of a specific type

javaimageswingjfilechooserfilefilter

提问by corvid

I have a program utilizing a JFileChooser. To be brief, the full program is a GUI which allows users to manipulate PNGs and JPGs. I would like to make it so that the JFileChooser instantly opens to the picture directory (windows). When the user opens their JFileChooser, it would open directly to the pictures library C:\Users\(USER)\Pictures

我有一个使用 JFileChooser 的程序。简而言之,完整的程序是一个 GUI,允许用户操作 PNG 和 JPG。我想让 JFileChooser 立即打开到图片目录(窗口)。当用户打开他们的 JFileChooser 时,它会直接打开图片库 C:\Users\(USER)\Pictures

Furthermore, it would be nice to ONLY show files of a specific type (PNGs and JPGs). Many programs seem to be able to do this; only allowing selection of specific files. Does JFileChooser allow such a thing? Currently, I am using a massively unreliable, run around method to reject non-PNGs/JPGs.

此外,最好只显示特定类型(PNG 和 JPG)的文件。许多程序似乎能够做到这一点;只允许选择特定文件。JFileChooser 是否允许这样的事情?目前,我正在使用一种非常不可靠的运行方法来拒绝非 PNG/JPG。

The following refers to the "browse" button of the GUI, in which a user will select their picture for editing and it will display it on the screen.

下面指的是GUI的“浏览”按钮,用户可以在其中选择要编辑的图片并将其显示在屏幕上。

    try {
       int val = filec.showOpenDialog(GridCreator.this);
       if(val==JFileChooser.APPROVE_OPTION) {
          File unfiltered_picture = filec.getSelectedFile();
          //get the extension of the file
          extension=unfiltered_picture.getPath();
          int index=extension.indexOf(".");
          extension=extension.substring(index+1, extension.length());
          //if the file is not jpg, png, or jpeg, reject it and send a message to the user.
          if(!extension.matches("[jJ][pP][gG]") && !extension.matches("[pP][nN][gG]") && !extension.matches("[jJ][pP][eE][gG]")) {
             JOptionPane.showMessageDialog(null,
                                           "cannot load file. File must be of type png, jpeg, or jpg. \n Your file is of type " + extension,
                                            "Error: improper file",
                                            JOptionPane.OK_OPTION);
           //if the file is of the proper type, display it to the user on the img JLabel.
           } else {
              finalImage = ImageIO.read(unfiltered_picture);
              ImageIcon imgIcon = new ImageIcon();
              imgIcon.setImage(finalImage);
              img.setIcon(imgIcon);
              img.invalidate();
              h_divide.setValue(0);
              v_divide.setValue(0);
           }
       }
   } catch(IOException exception) {
        exception.printStackTrace();
   }

Thank you.

谢谢你。

回答by Boris the Spider

You need to construct your JFileChooserwith the directory you want to start in and then pass a FileFilterinto it before setting visible.

您需要JFileChooser使用要开始的目录构建您的目录,然后FileFilter在设置可见之前将a 传递给它。

    final JFileChooser fileChooser = new JFileChooser(new File("File to start in"));
    fileChooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            final String name = f.getName();
            return name.endsWith(".png") || name.endsWith(".jpg");
        }

        @Override
        public String getDescription() {
            return "*.png,*.jpg";
        }
    });
    fileChooser.showOpenDialog(GridCreator.this);

This example filters for files ending in ".png" or ".jpg".

此示例过滤以“.png”或“.jpg”结尾的文件。

回答by E. Keller

Putting it all into a concise form, here is a flexible file chooser routine. It specifies initial directory and file type and it furnishes the result both as a file or a complete path name. You may also want to set your entire program into native interface mode by placing the setLookAndFeel command at the Main entry point to your program.

将所有内容简化为简洁的形式,这是一个灵活的文件选择器例程。它指定初始目录和文件类型,并将结果作为文件或完整路径名提供。您可能还想通过将 setLookAndFeel 命令放置在程序的 Main 入口点,将整个程序设置为本地界面模式。

String[] fileChooser(Component parent, String dir, String typeFile) {
    File dirFile = new File(dir);
    JFileChooser chooser = new JFileChooser();
    // e.g. typeFile = "txt", "jpg", etc.
    FileNameExtensionFilter filter = 
        new FileNameExtensionFilter("Choose a "+typeFile+" file",
            typeFile); 
    chooser.setFileFilter(filter);
    chooser.setCurrentDirectory(dirFile);
    int returnVal = chooser.showOpenDialog(parent);

    String[] selectedDirFile = new String[2];
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        // full path
        selectedDirFile[0] = chooser.getSelectedFile().getPath();
        // just filename
        selectedDirFile[1] = chooser.getSelectedFile().getName();
    }

    return selectedDirFile;
 }

try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
    e.printStackTrace();
}