CheckBoxTableCell changelistener not working

本秂侑毒 提交于 2019-11-27 14:33:15

The selectedProperty is inherited from Cell and it just indicates whether the Cell is selected in the UI component. Since you probably don't have cell selection enabled on your TableView, the cell never becomes selected. This isn't what you're looking for anyway; you want to know whether the CheckBox is selected, not the Cell.

The trick here is to use the selectedStateCallback property of the CheckBoxTableCell. This is a function that maps the index of the cell to a BooleanProperty. That BooleanProperty 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 it selectedProperty for demonstration) then you can do something like this:

final CheckBoxTableCell<Trainee, Boolean> ctCell = new CheckBoxTableCell<>();
ctCell.setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
    @Override
    public ObservableValue<Boolean> call(Integer index) {
        return table.getItems().get(index).selectedProperty();
    }
});

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 a BooleanProperty and observe it:

final CheckBoxTableCell<Trainee, Boolean> ctCell = new CheckBoxTableCell<>();
final BooleanProperty selected = new SimpleBooleanProperty();
ctCell.setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
    @Override
    public ObservableValue<Boolean> call(Integer index) {
        return selected ;
    }
});
selected.addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<? extends Boolean> obs, Boolean wasSelected, Boolean isSelected) {
        System.out.println(isSelected);
    }
});

As usual, all this code looks a lot nicer in Java 8.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!