I’m trying make a JFileChooser for selecting a folder. In this FileChooser, I’d like users to have the option of creating a new folder, and then selecting that. I’ve noticed that JFileChooser “Save” dialogs have a “new folder” button by default, but no similar button appears in “open” dialogs. Does anyone know how to add a “new folder” button to an “Open” dialog?
Specificially, I’d like to add the button to a dialog created using this code:
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileFilter( new FileFilter(){
@Override
public boolean accept(File f) {
return f.isDirectory();
}
@Override
public String getDescription() {
return "Any folder";
}
});
fc.setDialogType(JFileChooser.OPEN_DIALOG);
frame.getContentPane().add(fc);
frame.pack();
frame.setVisible(true);
Ok. In the end I solved this by using a “save” dialog instead of an “open” dialog. The standard save dialog already has a “new folder” button, but it also has a “Save as:” panel at the top, which I didn’t want. My solution was to use a standard save dialog, but to hide the “Save as” panel.
Here’s the code for the save dialog:
This part locates and hides the “Save as:” panel:
End result:
EDIT
There’s one quirk with this solution, which comes up if the user presses the approve button while there’s no directory currently selected. In this case the directory returned by the chooser will correspond to whatever directory the user was viewing, concatenated with the text in the (hidden) “save as:” panel. The resulting directory may be one that doesn’t exist. I handled this with the code below.