Reputation: 93
I'm trying to use a single TableView to display Customer (parent class) data stored in an ObservableList. This contains only Resident and Visitor (child classes) objects. Both child classes have different fields apart from the common Customer ones and I'm trying to show fields of all 3 classes on the table using this:
public void initialize(URL arg0, ResourceBundle arg1) {
custIDCol.setCellValueFactory(new PropertyValueFactory<Customer, Integer>("customerId"));
nameCol.setCellValueFactory(new PropertyValueFactory<Customer, String>("name"));
phoneCol.setCellValueFactory(new PropertyValueFactory<Customer, String>("phone"));
addressCol.setCellValueFactory(new PropertyValueFactory<Customer, String>("address"));
nationalityCol.setCellValueFactory(new PropertyValueFactory<Customer, String>("nationality"));
licenseCol.setCellValueFactory(new PropertyValueFactory<Customer, String>("drivingLicence"));
passportCol.setCellValueFactory(new PropertyValueFactory<Visitor, Integer>("passportNo"));
entryCol.setCellValueFactory(new PropertyValueFactory<Visitor, LocalDate>("entryDate"));
expiryCol.setCellValueFactory(new PropertyValueFactory<Visitor, LocalDate>("visaExpiryDate"));
qatarIDCol.setCellValueFactory(new PropertyValueFactory<Resident, Integer>("nationalId"));
custTableView.setItems(ProjectName.getCustomers());
}
NOTE: I gotta do it in this way as a project requirement.
Doing it in this way gives me an error like this:
Nov 18, 2020 11:52:36 AM javafx.scene.control.cell.PropertyValueFactory getCellDataReflectively
WARNING: Can not retrieve property 'passportNo' in PropertyValueFactory: javafx.scene.control.cell.PropertyValueFactory@1dba4623 with provided class type: class model.rental.customer.Resident
java.lang.IllegalStateException: Cannot read from unreadable property passportNo
Pretty sure this happens because it's tryna get a passportNo field from a Resident when only a Visitor will have this. I have tried surrounding it with a try catch to maybe somehow ignore the error but it didn't work. Is what I'm trying to achieve not possible using this method?
Upvotes: 1
Views: 222
Reputation: 93
Looks like @kleopatra's suggestion of using "custom factories that return values based on the actual type" worked. I did something like this and now the error doesn't show up anymore.
passportCol.setCellValueFactory(new Callback<CellDataFeatures<Visitor, Integer>, ObservableValue<Integer>>() {
public ObservableValue<Integer> call(CellDataFeatures<Visitor, Integer> p) {
if (p.getValue() instanceof Visitor)
return new ReadOnlyObjectWrapper(((Visitor) p.getValue()).getPassportNo());
else
return new ReadOnlyObjectWrapper("");
}
});
Upvotes: 1