This is it possible to implement this? I have File foo[] that has a list of 5 files. But I only want to copy foo[0] and foo[3] into File bar[] so that bar[] will only have 2 elements.
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]. 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. And from that list, I want the user to be able to select which files to attach to an email.
According to your comments, your JList
contains String
instances and not File
instances. 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
if you call getSelectedValues()
on your JList, you will get an array containing all items currently selected:
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. Try using getSelectedValuesList() method instead. If you need an array you can use list.getSelectedValuesList().toArray()