I'm trying to add a change listener to my CheckBoxTableCells but it doesn't seem to be working. I took the example for CheckBoxes figuring they would work the same way. However there is no output when i change its value. How would i add one correctly to a checkboxtablecell?
current code:
tc.setCellFactory(new Callback<TableColumn<Trainee, Boolean>, TableCell<Trainee, Boolean>>() {
@Override
public TableCell<Trainee, Boolean> call(TableColumn<Trainee, Boolean> p) {
final CheckBoxTableCell ctCell = new CheckBoxTableCell<>();
ctCell.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue ov, Boolean old_val, Boolean new_val) {
System.out.println(new_val);
}
});
return ctCell;
}
});
The
selectedProperty
is inherited fromCell
and it just indicates whether theCell
is selected in the UI component. Since you probably don't have cell selection enabled on yourTableView
, the cell never becomes selected. This isn't what you're looking for anyway; you want to know whether theCheckBox
is selected, not theCell
.The trick here is to use the
selectedStateCallback
property of theCheckBoxTableCell
. This is a function that maps the index of the cell to aBooleanProperty
. ThatBooleanProperty
is bound bidirectionally to the selected state of the check box.If your column is representing an actual property in your
Trainee
class (I'll just call itselectedProperty
for demonstration) then you can do something like this:Then the property in the
Trainee
class with be bidirectionally bound to the check box state. If you need to do more than just update your model object when the check box is selected/deselected, you can just observe that property.If you don't have a property in the
Trainee
class, you can just create aBooleanProperty
and observe it:As usual, all this code looks a lot nicer in Java 8.