[英]How to set all selected file absolute paths/names by JFileChooser into a JTextField
I have this small application with a JButton
to open a JFileChooser
to select multiple files. 我有一个带有
JButton
小型应用程序,用于打开JFileChooser
来选择多个文件。 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
). 因此,当我单击其
approve button
我应该能够将所有选定文件的绝对路径或名称设置为JTextField
(在我的情况下为jTextField1
)。
I know how to do this if I have selected only 1 file, but not with MULTIPLE SELECTED FILES 如果我只选择了1个文件,但没有选择多个文件,我知道该怎么做
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 {
}
}
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(files.length>=2)
If it is not possible to use java 8 you can create a method creating the complete string: 如果无法使用Java 8,则可以创建一个创建完整字符串的方法:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.