Reputation: 115
I have this small application with a JButton
to open a JFileChooser
to select multiple files. So when I click its approve button
I should be able to set all the selected files' absolute paths or names into a JTextField
(in my case it's jTextField1
).
I know how to do this if I have selected only 1 file, but not with MULTIPLE SELECTED FILES
How can I do this???
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser copy = new JFileChooser();
copy.setApproveButtonText("Copy");
copy.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
copy.setMultiSelectionEnabled(true);
int copyDialog = copy.showOpenDialog(null);
File[] files = copy.getSelectedFiles();
if (copyDialog == JFileChooser.APPROVE_OPTION) {
if(files.length>=2){
jTextField1.setText(files.toString()); // I need to set jTextField1's text with all the selected file paths or names
}else{
jTextField1.setText(copy.getSelectedFile().getAbsolutePath().toString());
}
} else {
}
}
Upvotes: 0
Views: 106
Reputation: 1835
You can collect and join the files with a stream:
Arrays.stream(files)
.map(File::getAbsolutePath)
.collect(Collectors.joining("\n"));
This would join the paths by a linebreak. You can change your delimiter to your need. In that case there is no need for your if(files.length>=2)
If it is not possible to use java 8 you can create a method creating the complete string:
private String getPaths(File[] files) {
if (files == null || files.length == 0) {
return "";
}
StringBuilder paths = new StringBuilder();
paths.append(files[0].getAbsolutePath());
for (int i = 1; i < files.length; i++) {
paths.append('\n');
paths.append(files[i].getAbsolutePath());
}
return paths.toString();
}
Upvotes: 2