How to add New Folder button in JFileChooser

I am trying to make JFileChooser to select a folder. In this FileChooser, I would like users to be able to create a new folder and then select it. I noticed that the "New Folder" button is set by default in the "Save" dialog box of JFileChooser, but a similar button does not appear in the "open" dialog boxes. Does anyone know how to add the "new folder" button to the "Open" dialog?

In particular, I would like to add a button to the 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); 
+4
source share
1 answer

Ok In the end, I solved this using the "save" dialog instead of the "open" dialog. The standard save dialog box already has a "new folder" button, but it also has a "Save As:" panel at the top, which I did not want. My solution was to use the standard save dialog, but to hide the Save As panel.

Here is the code for the save dialog:

  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.SAVE_DIALOG); fc.setApproveButtonText("Select"); frame.getContentPane().add(fc); frame.setVisible(true); 

This part finds and hides the Save As: panel:

  ArrayList<JPanel> jpanels = new ArrayList<JPanel>(); for(Component c : fc.getComponents()){ if( c instanceof JPanel ){ jpanels.add((JPanel)c); } } jpanels.get(0).getComponent(0).setVisible(false); frame.pack(); 

Final result:

enter image description here

EDIT

There is one quirk with this solution that appears if the user clicks the approve button until no directories are selected. In this case, the directory returned by the selection will correspond to any directory that the user was viewing, combined with the text in the (hidden) Save As: panel. The resulting directory may be one that does not exist. I processed this using the code below.

  File dir = fc.getSelectedFile(); if(!dir.exists()){ dir = dir.getParentFile(); } 
+3
source

All Articles