When I click on the button that activates the file chooser, and add the resulting file the panel color disappears. Does anyone know why this is happening?
import
Change last few lines of actionPerformed
method as below:
int returnVal = filechooser.showOpenDialog(new pan());
if(returnVal == JFileChooser.APPROVE_OPTION) {
//since its multiselection enabled,
//get the selected files not selected file
File[] files=filechooser.getSelectedFiles();
if(files != null){
for(File file: files){
listModel.addElement(file);
}
}
}
EDIT: Please make sure the proper exception handling for expected exceptions such as HeadlessException
is done appropriately.
EXPLANATION:
When browse panel is open, user may cancel the operation. In that case you shouldn't be reading the files as they were not selected. This is why, need to add a check on user selection, i.e. files were selected or not.
Since filechooser
is opened with setMultiSelectionEnabled
as true
, you need to get selected files as File[]
in place of getting a single file.
Since you are getting multiple files, you need to add each file in the listModel
. One way is to iterate the File array and add one file at a time. Other option could be to use Arrays.asList()
, get the list and add all the the files at once.
Hope this helps.