[英]How do I copy certain File elements in an array to a new File array?
This is it possible to implement this?这有可能实现吗? I have File foo[] that has a list of 5 files.
我有 File foo[] ,其中包含 5 个文件的列表。 But I only want to copy foo[0] and foo[3] into File bar[] so that bar[] will only have 2 elements.
但我只想将 foo[0] 和 foo[3] 复制到文件 bar[] 中,这样 bar[] 就只有 2 个元素。
My code gets the length of foo[], then if the index of the selected file equals the index for i, add foo[i] to bar[i].我的代码获取 foo[] 的长度,然后如果所选文件的索引等于 i 的索引,则将 foo[i] 添加到 bar[i]。 This is the possible code I've constructed:
这是我构建的可能代码:
for(int i = 0; i < foo.length; i++){
if(list_fileListing.getSelectedIndex() == i){
bar[i] = foo[i];
}
}
* list_fileListing.getSelectedIndex() holds the list of selected files from the JList.* The reason being is that I have a list of files that are selectable in a JList. * list_fileListing.getSelectedIndex() 包含从 JList 中选择的文件列表。*原因是我有一个 JList 中可选择的文件列表。 And from that list, I want the user to be able to select which files to attach to an email.
从该列表中,我希望用户能够 select 将哪些文件附加到 email。
if you call getSelectedValues()
on your JList, you will get an array containing all items currently selected:如果您在 JList 上调用
getSelectedValues()
,您将获得一个包含当前选定的所有项目的数组:
Object[] selectedObjects = list_fileListing.getSelectedValues();
for (int i = 0; i < selectedObjects.length; i++)
{
File aFile = (File)selectedObjects[i];
// attach this file
}
is this sufficient?这够了吗?
It looks like you're using Java7 since you have JList.getSelectedValues()
deprecated.看起来您正在使用 Java7,因为您已弃用
JList.getSelectedValues()
。 Try using getSelectedValuesList() method instead.尝试改用getSelectedValuesList()方法。 If you need an array you can use
list.getSelectedValuesList().toArray()
如果你需要一个数组,你可以使用
list.getSelectedValuesList().toArray()
According to your comments, your JList
contains String
instances and not File
instances.根据您的评论,您的
JList
包含String
实例而不是File
实例。 So you could do something like所以你可以做类似的事情
List<String> selectedFilesAsStrings = list_fileListing.getSelectedValuesAsList();
//selectedFilesAsStrings will never be null, but can be empty
List<File> selectedFiles = new ArrayList<File>( selectedFilesAsStrings.size() );
for( String fileName : selectedFilesAsStrings ){
selectedFiles.add( new File( fileName ) );
}
File[] bar = selectedFiles.toArray( new File[ selectedFiles.size() ] );
which will set the bar
array pointing to an array containing the selected File
instances这会将
bar
数组设置为指向包含所选File
实例的数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.