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

标签 java image swing jfilechooser filefilter

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

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

以下内容指的是 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();
   }

谢谢。

最佳答案

您需要使用要启动的目录构建 JFileChooser,然后在设置可见之前将 FileFilter 传递给其中。

    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);

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

关于java - 在指定目录启动 JFileChooser 并仅显示特定类型的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15954770/

相关文章:

html - 无法让图像拉伸(stretch)全宽

java - JTabbedPane 中固定位置或一行中的选项卡

java - 如何在java中使用Gremlin PipeLine副作用

image - OpenCV : Transparent area of imported . png 文件现在是白色的

image - 我正在尝试清除cgcontext上当前绘制的图像

java - 输出中的换行符

java - 尝试在方法中从 Jtable 中提取数据,但一无所获

java - Libgdx file.internal 文件未找到错误

java - 如何添加命令 XX :-UseSplitVerifier to an OSGi bundle built in CRXDE Lite (CQ5. 5)?

java - 围绕变量而不是类或方法进行同步