JFileChooser OK按下后如何退出?

Fra*_*sco 2 java swing jfilechooser

方案是,当选择单选按钮时,我打开一个JFileChooser来选择一个DIRECTORY,其中应该是一些文件.我正在尝试显示错误消息,我想再次显示目录选择器.这是代码(我在radiobutton更改时调用的函数):

private void JFileChooserOpen(java.awt.event.ActionEvent evt) {
    fileChooser.setCurrentDirectory(new java.io.File("."));
    fileChooser = new JFileChooser(); 
    fileChooser.setDialogTitle("Select a directory");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    fileChooser.setAcceptAllFileFilterUsed(false);

    int result = fileChooser.showOpenDialog(fileChooser);
    if (result == JFileChooser.APPROVE_OPTION) {
// here I'm calling a function that searches for specific files. 
// true these files are found, false, they are not.
        if (checkTheDir(fileChooser.getSelectedFile()))
        {
// assigning the path to a label
                thePath.setText(fileChooser.getSelectedFile().toString());
        }
        else
        {
// file not found
            JOptionPane.showMessageDialog(null, "File GuiRap not found!", 
                    "Controlla meglio", JOptionPane.WARNING_MESSAGE);
// what should I do, here, to open again the file dialog window?
// here I'm calling again this function, but surely is not a good practice!
            JFileChooserOpen(evt);
        }
// cancel button changes a radiobutton
    } else if (result == JFileChooser.CANCEL_OPTION) {
        rbnParams.setSelected(true);
    }
} 
Run Code Online (Sandbox Code Playgroud)

非常感谢!F.

alt*_*fox 5

创建时JFileChooser,覆盖其approveSelection方法(文档).

JFileChooser fileChooser = new JFileChooser() {
    @Override
    public void approveSelection() {
        // test your condition here
        if (checkTheDir(getSelectedFile())
            super.approveSelection();
        else
            JOptionPane.showMessageDialog(null, "File GuiRap not found!", 
                "Controlla meglio", JOptionPane.WARNING_MESSAGE);                
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,文件选择器不会关闭并重新打开,但会保持打开状态,直到满足所需条件(或取消执行).

此外,你应该提供一个parentComponentJOptionPane,而不是给它null.