Search code examples
javaswinguser-interfaceswingworker

Display an error message popup when file path on JFileChooser is invalid


I'd like to display an error message popup on top of a JFileChooser when user types in an invalid path.

I can make the popup show up by using JOptionPane, but not sure how to make it on top of the JFileChooser. I'd also like the program returns to the file chooser when user clicks 'OK' on the popup. How do I do these?

Edit: Is it possible to validate the path when user is typing?


Solution

  • You can try to override approveSelection if you want to show error message when File Chooser is opened:

    JFileChooser fc = new JFileChooser(){
    
            @Override
            public void approveSelection(){
                File f = getSelectedFile();
                if(!f.exists() ){                   
                    JOptionPane.showMessageDialog(null, "Error");                   
                }
            }           
        };
    
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setDialogTitle("Open test");
        fc.removeChoosableFileFilter(fc.getFileFilter());  //remove the default file filter
        FileFilter filter = new FileNameExtensionFilter("XML file", "xml");
    
        fc.addChoosableFileFilter(filter); //add XML file filter
    
        //show dialog
        int returnVal = fc.showOpenDialog(appFrame); 
    
        if(returnVal == JFileChooser.APPROVE_OPTION){/* ...  */}
    

    enter image description here

    Hope it will help you