如何在选择不受支持的文件后再次打开JFileChooser - Java

时间:2018-01-16 17:11:26

标签: java jfilechooser

如果Error_MESSAGEfilespublic static File[] files;,我想打开== null

Error_Message

如果用户按下“再次打开”,我想再次打开JFileChooser

JFileChooser

方法1:

private static void openFiles() {

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        files = getFiles(fileChooser.getSelectedFile(), new String[] {"png"}); //"files" is just this: public static File[] files;

        startPresentation();
    }
}

方法2:

private static void startPresentation() {
    try {
        Presentation.showView(Panels.start); //A method, that shows the "files" in a diashow

        SwingUtilities.invokeLater(() -> {
            frame.setVisible(true);
        });
    }catch(ExceptionInInitializerError | NoClassDefFoundError exception) {
        String[] options = new String[] {"Open again", "Close"};

        int message = JOptionPane.showOptionDialog(new JFrame(), "The files in the directory aren't supported", "Error!",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
        if(message == 0) {
            openFiles();
        }else {
            System.out.println("Close");
        }
    }
}

这是getFiles()方法:

private static File[] getFiles(File directory, String[] extensions) {

    FilenameFilter filter = new FilenameFilter() {

        @Override
        public boolean accept(File directory, String name) {
            for(String ext : extensions) {
                if(name.endsWith("." + ext)) {
                    return true;
                }
            }
            return false;
        }
    };

    File[] files = null;
    if(directory.isDirectory()) {
        files = directory.listFiles(filter);
    }

    return files;
}

但是如果我打开一个目录并且其中没有PNG-File,并且我想“再次打开”,则在打开文件夹后它总是会显示ERROR_MESSAGE(如果其中有一个PNG-File (如果我只打开一个文件夹并且其中有一个PNG-File,它就会起作用并显示该diashow。)

1 个答案:

答案 0 :(得分:0)

我自己找到了答案!

方法2 中,我添加了一个try / catch-block。我不知道为什么,但它适用于if / else。

比我有这个:

private static void startPresentation() {
    if(files.length > 0) {
        Presentation.showView(Panels.start);

        frame.setVisible(true);
    }else {
        String[] options = new String[] {"Open again", "Close"};

        int message = JOptionPane.showOptionDialog(new JFrame(), "The files in the directory aren't supported", "Error!",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
        if(message == 0) {
            openFiles();
        }else {
            System.out.println("Close");
        }
    }
}