CheckBoxTableCell checklist not working

I am trying to add a change listener to my CheckBoxTableCells, but it does not seem to work. I gave an example for CheckBoxes, believing that they will work the same. However, when I change its value, there is no way out. How can I add it correctly in 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; } }); 
+2
source share
1 answer

selectedProperty inherits from Cell , and it simply indicates whether Cell selected in the user interface component. Since you probably have no cell selection on your TableView , the cell will never be selected. In any case, this is not what you are looking for; You want to know if CheckBox selected, not Cell .

The trick here is to use the selectedStateCallback property for CheckBoxTableCell . This is a function that displays the cell index in BooleanProperty . That BooleanProperty bound bi-directionally to the selected state of the flag.

If your column represents the actual property in your Trainee class (I will just call it selectedProperty for demonstration), 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 must be bidirectionally bound to the state of the flag. If you need to do more than just update the model object when the checkbox is checked or unchecked, you can simply observe this property.

If you do not have a property in the Trainee class, you can simply create a BooleanProperty and watch 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.

+10
source

Source: https://habr.com/ru/post/974145/


All Articles