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

后端 未结 2 480
北荒
北荒 2021-01-29 03:25

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 JFileChoose

2条回答
  •  伪装坚强ぢ
    2021-01-29 03:26

    You need to construct your JFileChooser with the directory you want to start in and then pass a FileFilter into it before setting 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".

提交回复
热议问题