Reputation: 2135
I'm new to JavaFX so please bear with me. I am trying to have a TableView where some of the columns will be checkboxes. My intention is to bind these to boolean properties in a model object. The model object has the properties defined as SimpleBooleanProperty and have the getter/setter and property methods. I've verified that the table "sees" the model objects, because I'm binding some of the boolean columns as just text in the table, and sure enough, the table displays "true" or "false" as expected. However, I cannot get the checkbox to bind data in either direction. I've included some sample code below.
public class DataModel {
private SimpleBooleanProperty prop1;
private SimpleBooleanProperty prop2;
public boolean getProp1() {
return prop1.get();
}
public setProp1(boolean value) {
prop1.set(value);
}
public prop1() {
return prop1;
}
...
}
UI model logic:
...
private ObjectProperty<ObservableList<DataModel>> listProperty;
...
List<DataModel> list = new ArrayList<DataModel>();
... add some DataModel objects to list
final ObservableList<DataModel> obsList = FXCollections.observableArrayList(list);
listProperty.set(obsList);
UI logic:
...
TableView table = new TableView<DataModel>();
table.setEditable(true);
TableColumn<DataModel, String> boolAsStringCol = new TableColumn<DataModel, String>("Prop1");
boolAsStringCol.setCellValueFactory(new PropertyValueFactory<DataModel, String>("prop1"));
TableColumn<DataModel, Boolean> boolAsCbxCol = new TableColumn<DataModel, Boolean>("Prop2");
boolAsCbxCol.setCellValueFactory(new PropertyValueFactory<DataModel, Boolean>("prop2"));
boolAsCbxCol.setCellFactory(CheckBoxTableCell.forTableColumn(boolAsCbxCol));
boolAsCbxCol.setEditable(true);
table.getColumns().add(boolAsStringCol);
table.getColumns().add(boolAsCbxCol);
...
I can toggle the checkbox, but it does not appear to be binding the property to the checkbox. If I set a breakpoint, the setter does not get called when I check or uncheck the checkbox. Also, if I initialize the property to true when the object is created, it is not displayed as checked when the table is rendered.
Any suggestions are welcome. It seems like this should work, yet it does not.
Thanks.
Upvotes: 4
Views: 2964
Reputation: 1711
Instead of
boolAsCbxCol.setCellFactory(CheckBoxTableCell.forTableColumn(boolAsCbxCol));
Use
boolAsCbxCol.setCellFactory(CheckBoxTableCell.forTableColumn(boolAsCbxCol::getCellData));
Because the factory method you use is actually ignoring its argument and it's a bug https://bugs.openjdk.java.net/browse/JDK-8186287
Upvotes: 0
Reputation: 86
may be you need to add the following line to your code in DataModel
public SimpleBooleanProperty prop1Property() {return prop1;}
public SimpleBooleanProperty prop2Property() {return prop2;}
Upvotes: 2