I extended a JFileChooser
and overrode the approveSelection
method so that when a user chooses an invalid directory and then clicks on the Open button, an error message in a JOptionPane
will be displayed. But I want to make my JFileChooser
more user-friendly and make the Open button become disabled when a user clicks on an invalid directory and then become re-enabled when a user clicks on a valid directory. Is it possible to customize my JFileChooser
even further and get access to the Open button so that I can change the status of the button accordingly (possibly via a listener that listens for a directory selection)?
public class MyFileChooser extends JFileChooser {
private final JFrame mainFrame;
public MyFileChooser(JFrame mainFrame) {
this.mainFrame = mainFrame;
setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
@Override
public void approveSelection() {
if (/* directory is valid */) {
super.approveSelection();
return;
}
JOptionPane.showMessageDialog(mainFrame, "Invalid directory", "Error", JOptionPane.ERROR_MESSAGE);
}
}
See Question&Answers more detail:os