我有以下问题。我有一个CombBox
,它应该显示我的Quiz
类的名称(此类还有Tasks
的列表),我想从可用的选择中删除每一个Quiz
。我还创建了Quizzes
Teacher
,我只想在第二个Quizzes
中向所选所有者显示相应的ComboBox
(我没有到目前为止这个部分的问题。)
这是我的代码。
QuizComboBox
public class QuizComboBox extends ComboBox {
public QuizComboBox() {
List<Quiz> quizList = new QuizDao().getAllQuizes();
startTask(quizList);
Platform.runLater(() -> {
setCellFactory(new Callback<ListView<Quiz>, ListCell<Quiz>>() {
@Override
public ListCell<Quiz> call(ListView<Quiz> arg0) {
return new ListCell<Quiz>() {
@Override
protected void updateItem(Quiz item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
String quizText = item.getName();
setText(quizText);
}
}
};
}
});
});
}
public void startTask(List<Quiz> quizList){
Runnable task = () -> removeEmptyQuizzes(quizList);
Thread backgroundThread = new Thread(task);
backgroundThread.setDaemon(true);
backgroundThread.start();
}
private void removeEmptyQuizzes(List<Quiz> quizList){
for(Quiz q : quizList){
if(q.getTaskList().isEmpty()){
quizList.remove(q);
}
}
Platform.runLater(() -> setItems(FXCollections.observableArrayList(quizList)));
}
}
以下ComboBox
的监听者Teachers
更新了项目
private void teacherComboBoxListener(){
view.getTeacherComboBox().getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Teacher>() {
@Override
public void changed(ObservableValue<? extends Teacher> arg0, Teacher oldValue, Teacher newValue) {
view.getQuizComboBox().setValue(null);
if(newValue == view.getAllTeachersChoice()){
List<Quiz> quizList = new QuizDao().getAllQuizes();
view.getQuizComboBox().startTask(quizList);
}
else {
Teacher selectedTeacher = (Teacher) view.getTeacherComboBox().getSelectionModel().getSelectedItem();
List<Quiz> quizList = selectedTeacher.getQuizList();
view.getQuizComboBox().startTask(quizList);
}
}
});
}
我收到以下异常
Exception in thread "Thread-5" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at view.controlElements.QuizComboBox.removeEmptyQuizzes(QuizComboBox.java:51)
at view.controlElements.QuizComboBox.lambda$startTask$1(QuizComboBox.java:44)
at java.lang.Thread.run(Thread.java:745)
编辑:我已经尝试了@ fabian的解决方案,它适用于相当大的错误,它会从我的数据库中删除所有Quizzez
空TaskList
。
private void removeEmptyQuizzes(List<Quiz> quizList){
for(Iterator<Quiz> iterator = quizList.iterator(); iterator.hasNext();){
Quiz q = iterator.next();
if(q.getTaskList().isEmpty()){
iterator.remove(); // removed from db also
}
}
Platform.runLater(() -> setItems(FXCollections.observableArrayList(quizList)));
}