1

用户可以使用 JFileChooser 选择一个或多个 mp3 文件吗?

我只能选择用户一个文件,使用这种方法。

4

2 回答 2

6

只需将多选设置为 true 并将选择模式设置为 JFileChooser.FILES_AND_DIRECTORIES ,它将适用于多个文件和目录中的所有文件:

fileChooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
fileChooser.setMultiSelectionEnabled(true);

然后以这种方式检索所有文件:

fileChooser.getSelectedFiles();
于 2012-08-17T08:24:39.567 回答
2

My understanding of your requirement is:

  • User can choose one or multiple files
  • If a single file is chosen, then you work with that file
  • If multiple files are chosen then you would create a playlist and work with this playlist.

If this is what you want, I think the following might work for this scenario. Note that I've left the implementation to you because you know how to create a playlist or how to create a single file and feed it to your player.

/** This method returns a set of files chosen by the user. 
  * Returns null if selection is cancelled 
  **/
private File[] openFiles(){

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(true);
    fileChooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );

    int optionChosen = fileChooser.showOpenDialog(this);

    return (optionChosen == JFileChooser.CANCEL_OPTION) ? null : fileChooser.getSelectedFiles();
}

public void actionPerformed(ActionEvent e){
    File[] selectedFiles = openFiles();

    if(selectedFiles == null){
       //handleNoFileChosen
    }else if(selectedFiles.length == 1){
        //handle single file selected
    }else{
        //handle creating playlist
    }
}
于 2012-08-17T09:05:40.463 回答