最终,我设法在GUI中的复选框上单击时进行跟踪。但是现在它不会将CheckBox的正确值加载到gui中。谁能看到哪里出了问题? :)
roadtrainCol.setCellValueFactory(
new Callback<CellDataFeatures<Spot,Boolean>,ObservableValue<Boolean>>()
{
public ObservableValue<Boolean> call(CellDataFeatures<Spot, Boolean> param) {
return param.getValue().getRoadtrain();
}
});
roadtrainCol.setCellFactory(col -> {
CheckBoxTableCell<Spot, Boolean> cell = new CheckBoxTableCell<>(index -> {
BooleanProperty active = new SimpleBooleanProperty();
active.addListener((obs, wasActive, isNowActive) -> {
System.out.println("del");
rettedeSpots(tableViewId.getItems().get(index).getId());
});
return active ;
});
return cell ;
});
最佳答案
您正在创建新的BooleanProperty
。这些属性将始终使用false
初始化。cellFactory
不是添加侦听器的地方。而是将侦听器添加到项目。
roadtrainCol.setCellValueFactory(
new Callback<CellDataFeatures<Spot, Boolean>, ObservableValue<Boolean>>() {
public ObservableValue<Boolean> call(CellDataFeatures<Spot, Boolean> param) {
return param.getValue().getRoadtrain();
}
});
roadtrainCol.setCellFactory(CheckBoxTableCell.forTableColumn(roadtrainCol));
ChangeListener<Boolean> roadTrainChangeListener = (observable, oldValue, newValue) -> {
Spot spot = (Spot) ((ReadOnlyProperty) observable).getBean();
System.out.println("del");
rettedeSpots(spot.getId());
};
// add/remove listeners when Spots are added to/removed from the list
tableViewId.getItems().addListener((ListChangeListener.Change<? extends Spot> c) -> {
while (c.next()) {
for (Spot s : c.getRemoved()) {
s.getRoadtrain().removeListener(roadTrainChangeListener);
}
for (Spot s : c.getAddedSubList()) {
s.getRoadtrain().addListener(roadTrainChangeListener);
}
}
});
// add listeners to items already in the list
for (Spot s : tableViewId.getItems()) {
s.getRoadtrain().addListener(roadTrainChangeListener);
}
请注意,这仅在将包含
Spot
的SimpleBooleanProperty
实例分配为bean
时有效,例如Spot() {
this.roadtrain = new SimpleBooleanProperty(this, "roadtrain");
}
要么
Spot(boolean roadtrain) {
this.roadtrain = new SimpleBooleanProperty(this, "roadtrain", roadtrain);
}
我只是使用
bean
来避免为每个项目创建新的侦听器。还可以考虑遵循JavaFX属性的命名约定:
属性获取器命名为
<propertyName>Property
(不是get<capitalFirstLetterPropertyName>
)属性值的获取程序名为
get<capitalFirstLetterPropertyName>
属性值的设置器名为
set<capitalFirstLetterPropertyName>