Reputation: 341
I find a problem when dealing with tableview that need a centered checkbox column. I am able to create a column with checkbox. I also want to set property in my model according to that checkbox value. I did it with the following code:
isCanceledCol.setCellValueFactory(new Callback<CellDataFeatures<TransactionModel,CheckBox>,ObservableValue<CheckBox>>() {
@Override
public ObservableValue<CheckBox> call(final CellDataFeatures<TransactionModel, CheckBox> p) {
CheckBox cb = new CheckBox();
cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
p.getValue().setIsCanceled(t1.booleanValue());
}
}
);
canceledCB.add(cb);
return new SimpleObjectProperty(cb);
}
The problem with the code above is, the checkboxes appear with left alignment. I want to make it centered, but I also want to keep the changed event of the checkbox to change my model property ( p.getValue().setIsCanceled(t1.booleanValue()); ).
I really appreciate help from you guys.
Regards, Chrisma Andhika
Upvotes: 3
Views: 4109
Reputation: 1320
JavaFX Ensemble (javafx sample) has the perfect code that you are trying to use. Plus they have given a better way of using a CheckBox
in a TableView
.
The point is to extent TableCell
used by the TableView
control. For creating a CheckBox
column following should be created and used:
//CheckBoxTableCell for creating a CheckBox in a table cell
public static class CheckBoxTableCell<S, T> extends TableCell<S, T> {
private final CheckBox checkBox;
private ObservableValue<T> ov;
public CheckBoxTableCell() {
this.checkBox = new CheckBox();
this.checkBox.setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
setGraphic(checkBox);
}
@Override public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setGraphic(checkBox);
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().unbindBidirectional((BooleanProperty) ov);
}
ov = getTableColumn().getCellObservableValue(getIndex());
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().bindBidirectional((BooleanProperty) ov);
}
}
}
}
The setAlignment(Pos.CENTER)
will set your control in the center of the cell.
Upvotes: 3