我有以下课程:
public class Person {
private final StringProperty firstName;
private final StringProperty lastName;
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public StringProperty getName() {
return new SimpleStringProperty(firstName.get() + " " + lastName.get());
}
}
然后我有一个TableView,我在一列中显示两个名称:
@FXML
private TableView<Person> personTable;
@FXML
private TableColumn<Person, String> name;
@FXML
private void initialize() {
name.setCellValueFactory(cellData -> cellData.getValue().getName());
personTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldVal, newVal) -> showDetails(newVal));
}
现在我可以对Person对象进行更改,但它们不会显示在TableView列中。当我再次打开编辑窗口时,我看到了新值,但在我的TableView中,我看到了旧值。我该怎么办呢?
答案 0 :(得分:4)
待办事项
public class Person {
private final ReadOnlyStringWrapper name = new ReadOnlyStringWrapper();
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
public Person() {
name.bind(Bindings.concat(firstName, " ", lastName));
// existing code...
}
// existing code...
public ReadOnlyStringProperty nameProperty() {
return name.getReadOnlyProperty();
}
public final String getName() {
return name.get();
}
}
然后你可以做
@FXML
private TableColumn<Person, String> name;
@FXML
private void initialize() {
name.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
}
或者,您可以完全从Person
类中省略全名,只需在单元格值工厂中创建所需的绑定:
name.setCellValueFactory(cellData -> Bindings.concat(
cellData.getValue().firstNameProperty(),
" ",
cellData.getValue().lastNameProperty()));