我正在开发一个用于学生的会计出勤的程序。我需要一个带有第一列的表格-一个学生列表(TableColumn)和我动态生成的下一列(演讲列表)。在行和列的交点处-ComboBox。我找到了如何为一种类型(TableView >>)动态生成列的方法,但没有找到适合我的情况的解决方案。
我有个主意要再开一个班
class Row{
StringProperty audience;
ObservableList<Attendence> lectures;
}
但不知道如何实现。
如何解决这个问题呢??
最佳答案
您的想法基本上是正确的:
public class Row{
private final StringProperty audience = new SimpleStringProperty();
private final List<ObjectProperty<Attendance>> lectures = new ArrayList<>();
public Row(String audience, int numAttendances) {
setAudience(audience);
for (int i = 0 ; i < numAttendances ; i++) {
lectures.add(new SimpleObjectProperty<>());
}
}
public List<ObjectProperty<Attendance>> getLectures() {
return lectures ;
}
public StringProperty audienceProperty() {
return audience ;
}
public final String getAudience() {
return audienceProperty().get();
}
public final void setAudience(String audience) {
audienceProperty().set(audience);
}
}
现在,您可以按照以下步骤设置表格:
int numLectures = ... ;
TableView<Row> table = new TableView<>();
TableColumn<Row, String> audienceCol = new TableColumn<>("Audience");
audienceCol.setCellValueFactory(cellData -> cellData.getValue().audienceProperty());
table.getColumns().add(audienceCol);
for (int i = 0 ; i < numLectures ; i++) {
TableColumn<Row, Attendance> col = new TableColumn<>("Attendance "+ (i+1));
final int colIndex = i ;
col.setCellValueFactory(cellData -> cellData.getValue().getLectures().get(colIndex));
table.getColumns().add(col);
}