简体   繁体   English

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

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

I have a program utilizing a JFileChooser. 我有一个利用JFileChooser的程序。 To be brief, the full program is a GUI which allows users to manipulate PNGs and JPGs. 简而言之,完整的程序是一个GUI,它允许用户操纵PNG和JPG。 I would like to make it so that the JFileChooser instantly opens to the picture directory (windows). 我想这样做,以便JFileChooser立即打开图片目录(Windows)。 When the user opens their JFileChooser, it would open directly to the pictures library C:\\Users\\(USER)\\Pictures 当用户打开其JFileChooser时,它将直接打开图片库C:\\ Users \\(USER)\\ Pictures

Furthermore, it would be nice to ONLY show files of a specific type (PNGs and JPGs). 此外,最好只显示特定类型的文件(PNG和JPG)。 Many programs seem to be able to do this; 许多程序似乎都可以做到这一点。 only allowing selection of specific files. 仅允许选择特定文件。 Does JFileChooser allow such a thing? JFileChooser允许这样的事情吗? Currently, I am using a massively unreliable, run around method to reject non-PNGs/JPGs. 目前,我正在使用一种非常不可靠的解决方法来拒绝非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. 谢谢。

You need to construct your JFileChooser with the directory you want to start in and then pass a FileFilter into it before setting visible. 您需要使用要在其中开始的目录构造JFileChooser ,然后将FileFilter传递到其中,然后再将其设置为visible。

    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”结尾的文件。

Read the API: http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html 阅读API: http : //docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html

At the very top of the javadoc page is an example of nearly exactly what you want to do: 在javadoc页面的顶部,几乎是您想要执行的操作的示例:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

The class that you are looking for in general is FileFilter , which is abstract. 通常,您要查找的类是FileFilter ,它是抽象的。 See the javadoc: http://docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/FileFilter.html 请参阅Javadoc: http : //docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/FileFilter.html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM