How to add CheckBox's to a TableView in JavaFX

前端 未结 13 505
日久生厌
日久生厌 2020-11-30 00:32

In my Java Desktop Application I have a TableView in which I want to have a column with CheckBoxes.

I did find where this has been done http://www.jonathangiles.net/

相关标签:
13条回答
  • 2020-11-30 01:29

    for me, works with this solution:

    Callback<TableColumn, TableCell> checkboxCellFactory = new Callback<TableColumn, TableCell>() {
    
            @Override
            public TableCell call(TableColumn p) {
                return new CheckboxCell();
            }
        };
        TableColumn selectColumn = (TableColumn) tbvDatos.getColumns().get(1);
        selectColumn.setCellValueFactory(new PropertyValueFactory("selected"));
        selectColumn.setCellFactory(checkboxCellFactory);
    

    and the tableCell:

    public class CheckboxCell extends TableCell<RowData, Boolean> {
    CheckBox checkbox;
    
    @Override
    protected void updateItem(Boolean arg0, boolean arg1) {
        super.updateItem(arg0, arg1);
            paintCell();
    }
    
    private void paintCell() {
        if (checkbox == null) {
            checkbox = new CheckBox();
            checkbox.selectedProperty().addListener(new ChangeListener<Boolean>() {
    
                @Override
                public void changed(ObservableValue<? extends Boolean> ov,
                        Boolean old_val, Boolean new_val) {
                    setItem(new_val);
                    ((RowData)getTableView().getItems().get(getTableRow().getIndex())).setSelected(new_val);
                }
            });
        }
        checkbox.setSelected(getValue());
        setText(null);
        setGraphic(checkbox);
    }
    
    private Boolean getValue() {
        return getItem() == null ? false : getItem();
    }
    }
    

    if you dont need to make the checkbox with edit event

    0 讨论(0)
提交回复
热议问题