我希望我JFileChooser
允许选择多个文件,但对可以同时选择的文件数量有限制。
Ideally I would like to constrain the selection in real-time, with priority given to the most-recently selected file, ie when a 3rd file is selected, the 1st file (ie the one that was selected earliest) should be deselected automatically.
我认为PropertyChangeListener
像这样的一个会起作用:
public static void main(String[] args) throws IOException {
final JFileChooser fc = new JFileChooser(didir);
fc.setMultiSelectionEnabled(true);
fc.addPropertyChangeListener(new PropertyChangeListener() {
private final Set<File> selected = Sets.newLinkedHashSet();
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
File[] selectedFiles = fc.getSelectedFiles();
if (selectedFiles.length > 2) {
selected.addAll(Arrays.asList(selectedFiles));
int numToRemove = Math.max(0, selected.size() - 2);
Iterables.removeIf(Iterables.limit(selected, numToRemove),
Predicates.alwaysTrue());
fc.setSelectedFiles(selected.toArray(new File[0]));
}
}
}
});
fc.showOpenDialog(null);
}
但是调用fc.setSelectedFiles()
没有效果(虽然它触发了一个事件,但它不会更新列表中的选择。)
有没有办法在JFileChooser
打开时以编程方式强制更改选择?还是有另一种方法来限制选择的大小?