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

后端 未结 2 482
北荒
北荒 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:37

    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.

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

提交回复
热议问题