在Java中使用JFileChooser
类时遇到问题。我想从不同的目录中选择多个文件,但我不知道是否可以使用此类。
我知道有一种方法setMultiSelectionEnabled(true)
支持多重选择,但是在同一目录中只是多重选择。
如何在同一JFileChooser
窗口的不同目录中选择多个文件(至少两个)?
这是我实际使用的课程:
public class DialogFileGraph extends JPanel {
/**
*
*/
private static final long serialVersionUID = 449534361312105564L;
/**
* String constant for new line
*/
private static final String NEWLINE = "\n";
/**
* empty constant for filename
*/
private static final String EMPTY = "empty";
/**
* logger
*/
private static final Logger LOGGER = LogManager.getLogger(DialogFileGraph.class);
/**
*
*/
private final JFileChooser fc = new JFileChooser();
/**
*
*/
private String file = EMPTY;
/**
* @param filepath
* path to the file
* @param compare
* Boolean
*/
public DialogFileGraph(File filepath, Boolean compare) {
super(new BorderLayout());
try{
fc.setFileFilter(new FileNameExtensionFilter("NetCDF files", "nc"));
if (!compare){
// Case for choosing one file
fc.setCurrentDirectory(filepath);
fc.setDialogTitle(Messages.DialogFileGraph_File_Choice);
fc.setDialogType(JFileChooser.OPEN_DIALOG);
fc.setEnabled(true);
fc.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint());
fc.setVisible(true);
fc.setMultiSelectionEnabled(false);
final int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File realFile = fc.getSelectedFile();
file = realFile.getAbsolutePath();
} else {
JOptionPane.showMessageDialog(null,
Messages.DialogFileGraph_Open_Cancelled + NEWLINE);
file = EMPTY;
}
} else {
// Case for choosing multiple files
fc.setCurrentDirectory(filepath);
fc.setDialogTitle(Messages.DialogFileGraph_Multi_Files_Choice);
fc.setDialogType(JFileChooser.OPEN_DIALOG);
fc.setEnabled(true);
fc.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint());
fc.setVisible(true);
fc.setMultiSelectionEnabled(true);
final int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File[] realFiles = fc.getSelectedFiles();
for(int i=0;i<realFiles.length-1;i++){
file = realFiles[i].getAbsolutePath()+";"+realFiles[i+1].getAbsolutePath();
}
} else {
JOptionPane.showMessageDialog(null,
Messages.DialogFileGraph_Open_Cancelled + NEWLINE);
file = EMPTY;
}
}
} catch (HeadlessException ex){
LOGGER.error(ex.getLocalizedMessage());
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event dispatch thread.
* @return String file
*/
public String getFile() {
return file;
}