How to add CheckBox's to a TableView in JavaFX

前端 未结 13 525
日久生厌
日久生厌 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:17

    You need to set a CellFactory on the TableColumn.

    For example:

    Callback, TableCell> booleanCellFactory = 
                new Callback, TableCell>() {
                @Override
                    public TableCell call(TableColumn p) {
                        return new BooleanCell();
                }
            };
            active.setCellValueFactory(new PropertyValueFactory("active"));
            active.setCellFactory(booleanCellFactory);
    
    class BooleanCell extends TableCell {
            private CheckBox checkBox;
            public BooleanCell() {
                checkBox = new CheckBox();
                checkBox.setDisable(true);
                checkBox.selectedProperty().addListener(new ChangeListener () {
                    public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                        if(isEditing())
                            commitEdit(newValue == null ? false : newValue);
                    }
                });
                this.setGraphic(checkBox);
                this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                this.setEditable(true);
            }
            @Override
            public void startEdit() {
                super.startEdit();
                if (isEmpty()) {
                    return;
                }
                checkBox.setDisable(false);
                checkBox.requestFocus();
            }
            @Override
            public void cancelEdit() {
                super.cancelEdit();
                checkBox.setDisable(true);
            }
            public void commitEdit(Boolean value) {
                super.commitEdit(value);
                checkBox.setDisable(true);
            }
            @Override
            public void updateItem(Boolean item, boolean empty) {
                super.updateItem(item, empty);
                if (!isEmpty()) {
                    checkBox.setSelected(item);
                }
            }
        }
    

提交回复
热议问题