Reputation: 10253
I have a TableView
populated with a custom object; the table displays the properties of that object.
My question is how can I bind a different property to the column based on the value of another property for that row?
For example, suppose I have this object:
public class MyObject() {
private SimpleStringProperty name = new SimpleStringProperty("");
private SimpleStringProperty type = new SimpleStringProperty("");
}
Now in the TableView
, I have the two columns:
+---------+--------+
| NAME | TYPE |
+---------+--------+
| Robert | Mgr |
+---------+--------+
However, if type = "Something"
, I want the Type
column to actually display the value of the name
property instead:
+---------+--------+
| NAME | TYPE |
+---------+--------+
| Robert | Robert |
+---------+--------+
I am unclear how to go about setting a different PropertyValueFactory
based on the value of another property within the same object instance.
Upvotes: 0
Views: 842
Reputation: 10253
I was able to use the following solution as well:
colType.setCellValueFactory(param -> {
if (param.getValue() != null) {
if (param.getValue().getType().equals("Something")) {
return new SimpleStringProperty(param.getValue().getName);
} else {
return new SimpleStringProperty(param.getValue().getType());
}
} else {
return new SimpleStringProperty("");
}
});
Upvotes: 0
Reputation: 4209
You should be able to do something like this:
Edit to show column definition - this needs to take the object as a whole, not a string.
@FXML
private TableColumn<MyObject,MyObject> changingColumn;
...
//Where you initialize the table
changingColumn.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<>(cellData.getValue()));
changingColumn.setCellFactory(tc -> new TableCell<MyObject, MyObject>() {
@Override
public void updateItem(MyObject item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText("");
} else if ("something".equals(item.getType())){
setText(item.getName());
}else {
setText(item.getType());
}
}
});
Upvotes: 1