【问题标题】:Starting a JFileChooser at a specified directory and only showing files of a specific type在指定目录启动 JFileChooser 并仅显示特定类型的文件
【发布时间】:2013-04-11 17:07:13
【问题描述】:

我有一个使用 JFileChooser 的程序。简而言之,完整的程序是一个允许用户操作 PNG 和 JPG 的 GUI。我想让 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();
   }

谢谢。

【问题讨论】:

    标签: java image swing jfilechooser filefilter


    【解决方案1】:

    您需要使用您要开始的目录来构建您的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”结尾的文件。

    【讨论】:

    • 不错,但是有没有办法让它直接进入 C:\Users(user)\Pictures 目录?
    • 在构造函数的new File中指定。代码显示“文件开始”的地方。像 new File(System.getProperty("user.home"), "Pictures") 这样的东西应该可以工作。
    • Pictures 目录的位置高度依赖于系统,因此没有真正的 Java 方法可以找到它。也就是说,您可以使用FileSystemView docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/… 中的方法来查找用户的主目录。从那里开始,它是一个基于 Windows xp/7/8/9/10/etc 的猜谜游戏......
    【解决方案2】:

    简明扼要,这是一个灵活的文件选择器例程。它指定初始目录和文件类型,并将结果提供为文件或完整路径名。您可能还想通过将 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多