如何检测由ObservableList填充的tableView中的数据更改(不仅是添加/删除,还包括更改对象的属性),其中包含具有此类属性的对象:
public class Car{
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty brand = new SimpleStringProperty();
private SimpleStringProperty engine = new SimpleStringProperty();
private SimpleBooleanProperty navi = new SimpleBooleanProperty();
private SimpleBooleanProperty available = new SimpleBooleanProperty();
private SimpleDoubleProperty liters = new SimpleDoubleProperty();
private SimpleIntegerProperty power = new SimpleIntegerProperty();
(...)
}
在Controller类中,这是我将它们绑定在一起的方式:
class MainController
{
@FXML
public void initialize()
{
idColumn.setCellValueFactory(new PropertyValueFactory<Car, Integer>("id"));
engineColumn.setCellValueFactory(new PropertyValueFactory<Car, String>("engine"));
brandColumn.setCellValueFactory(new PropertyValueFactory<Car, String>("brand"));
naviColumn.setCellValueFactory(new PropertyValueFactory<Car, Boolean>("navi"));
availableColumn.setCellValueFactory(new PropertyValueFactory<Car, Boolean>("available"));
powerColumn.setCellValueFactory(new PropertyValueFactory<Car, Integer>("power"));
fuelColumn.setCellValueFactory(new PropertyValueFactory<Car, Double>("liters"));
carModel.getObservableList().add(new Car(213,"FIAT","1.9 JTD",true,true,32.4,132));
tableView.setItems(carModel.getObservableList());
}
我试图为observableList添加初始化方法监听器,但不幸的是它只检测从列表中添加和删除对象。我希望只要对象中的任何属性发生更改,侦听器就会更新tableView
carModel.getObservableList().addListener((Change<? extends Car> c) -> {
while (c.next()) {
if (c.wasAdded()) {
System.out.println("Added:");
c.getAddedSubList().forEach(System.out::println);
System.out.println();
}
if (c.wasRemoved()) {
System.out.println("Removed:");
c.getRemoved().forEach(System.out::println);
System.out.println();
}
if (c.wasUpdated()) {
System.out.println("Updated:");
carModel.getObservableList().subList(c.getFrom(), c.getTo()).forEach(System.out::println);
System.out.println();
}
}
});
我在论坛上发现了这样的解决方案,就像我说的那样只检测到添加/删除对象
答案 0 :(得分:1)
如果您只需要更改其中一个属性的事实,最简单的方法是将所有属性连接到一个ObservableValue
。
在Car
班级中有这种方法:
ObservableValue changeProperty() {
return Bindings.concat(id, brand, engine, navi, available, liters, power);
}
在客户端你只是听它:
car.changeProperty().addListener(new ChangeListener() {
@Override
void changed(ObservableValue observable, Object oldValue, Object newValue) {
// one of property was changed, do something
}
})
如果您需要检测所有车辆之间的变化,同样如此:
ObservableValue changeProperty() {
return Bindings.concat(car1.changeProperty(), car2.changeProperty(), carN.changeProperty());
}