Panel losing color

后端 未结 2 1842
自闭症患者
自闭症患者 2021-01-29 07:34

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         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-29 07:48

    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:

    1. 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.

    2. Since filechooser is opened with setMultiSelectionEnabled as true, you need to get selected files as File[] in place of getting a single file.

    3. 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.

提交回复
热议问题