如您所见,有一些自定义单元格 (+) 不是课程。它们是按钮。
我有两节课:
public class Lesson {
private Room schoolRoom;
private Room teachingRoom;
private TeacherSpecialization teachingInfo;
private WeekDay weekDay;
private int schoolHour;
}
和
public class ClassHour {
Lesson[] dayLessons = new Lesson[18];
private int hour;
public ClassHour(int hour) {
this.hour = hour;
}
}
使用此代码,我将我的课程对象转换为 ClassHour 对象,因为我使用 ClassHour 对象将课程保存在表中:
public ObservableList<ClassHour> convertToClassHour(List<Lesson> lessons) {
ObservableList<ClassHour> classHours = FXCollections.observableArrayList();
// Converting Lessons to ClassHour objects.
lessons.forEach(lesson -> {
ClassHour classHour = classHours.stream().filter(ch -> ch.getHour() == lesson.getSchoolHour()).findFirst().orElse(null);
if (classHour == null) {
classHour = new ClassHour(lesson.getSchoolHour());
classHours.add(classHour);
}
classHour.getDayLessons()[lesson.getWeekDay().ordinal()] = lesson;
});
return classHours;
}
最后一步是显示表格中的数据:
private void showLessons(String roomNr) throws Exception {
try {
// lessons.addListener((ListChangeListener) e -> repopulate(lessons, classHours));
ArrayList<Lesson> allLessonsByRoomNr = db.getAllLessonsByRoomNr(roomNr);
ObservableList<ClassHour> classHours = db.convertToClassHour(allLessonsByRoomNr);
for (int i = 0; i < 5; i++) {
int day = i;
TableColumn<ClassHour, Lesson> dayColumn = new TableColumn<>(WeekDay.values()[i].name());
dayColumn.setSortable(false);
dayColumn.setCellValueFactory(param -> new SimpleObjectProperty(param.getValue().getDayLessons()[day]));
dayColumn.setCellFactory((TableColumn<ClassHour, Lesson> param) -> new TableCell<ClassHour, Lesson>() {
@Override
protected void updateItem(Lesson item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (!empty) {
if (item != null) {
setText(item.toString());
} else {
Button btn = new Button("+ ADD");
btn.setOnAction(e -> {
tableLessons.getSelectionModel().select((ClassHour) getTableRow().getItem());
showAdd(day, ((ClassHour) getTableRow().getItem()).getHour(), btn);
});
setGraphic(new StackPane(btn));
}
}
}
});
tableLessons.getColumns().addAll(dayColumn);
}
tableLessons.setItems(classHours);
} catch (Exception ex) {
showResultDialog("An error has occured:", ex.getMessage());
}
}
我正在苦苦挣扎的问题是自定义单元格(+ 按钮)。出于某种原因,我无法在两节课之间画出它们。在下面的例子中,第 10 到 16 节课(星期一)之间应该有 5 个单元格/行。