For a simple Swing application for merging PDFs with Apache PDFBox I’m using a JFileChooser to select one or multiple PDF files and add it/them to a JList.
No problems so far.
What bothers me is that the previous selection persists in the JFileChooser when I click the button to add another file/files again, I do not want this, the selection should initially be empty.
I tried this but it neither works nor throws an exception:
pdfFileChooser.setSelectedFile(null);
Here is the relevant code:
pdfFileChooser.setAcceptAllFileFilterUsed(false);
pdfFileChooser.setMultiSelectionEnabled(true);
pdfFileChooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File arg0) {
return arg0.getName().endsWith(".pdf");
}
@Override
public String getDescription() {
return "*.pdf";
}
} );
JButton btnAddFile = new JButton("Add file");
btnAddFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(pdfFileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
addFileToList(pdfFileChooser.getSelectedFiles());
pdfFileChooser.setSelectedFile(null);
}
}
});
private void addFileToList(File[] filesToAdd) {
if((filesToAdd != null) && (filesToAdd.length > 0)) {
DefaultListModel model = (DefaultListModel)listFiles.getModel();
for(File file : filesToAdd) {
if(!model.contains(file)) {
model.addElement(file);
}
}
}
}
How can I remove the selection from the JFileChooser so no file/files is/are initially selected?
This is, IMHO,
a bug.(As has been kindly pointed out, “bug” might be to strong a word as the API does not state what would happen if you passed null to the
selectedFilemethod. Instead, it’s probably more reasonable to suggest that it is a missing feature)Try something like this…
Basically, the change of the selected file seems to be UI dependent and relies on the
SELECTED_FILE_CHANGED_PROPERTYproperty change event. What seems to happen is that it’s ignoring anullreference when it comes to changing (in particular) the selected file text field.I tested this using Metal and Windows look and feel