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?