How to add CheckBox's to a TableView in JavaFX

2019-01-10 15:33发布

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/javafx/2.0/CellFactories/ but as the download is not available and because I don't know how soon Jonathan Giles will answer my email I thought I'd ask...

How do I put a CheckBox in a cell of my TableView?

12条回答
贼婆χ
3楼-- · 2019-01-10 15:58

You need to set a CellFactory on the TableColumn.

For example:

Callback<TableColumn<TableData, Boolean>, TableCell<TableData, Boolean>> booleanCellFactory = 
            new Callback<TableColumn<TableData, Boolean>, TableCell<TableData, Boolean>>() {
            @Override
                public TableCell<TableData, Boolean> call(TableColumn<TableData, Boolean> p) {
                    return new BooleanCell();
            }
        };
        active.setCellValueFactory(new PropertyValueFactory<TableData,Boolean>("active"));
        active.setCellFactory(booleanCellFactory);

class BooleanCell extends TableCell<TableData, Boolean> {
        private CheckBox checkBox;
        public BooleanCell() {
            checkBox = new CheckBox();
            checkBox.setDisable(true);
            checkBox.selectedProperty().addListener(new ChangeListener<Boolean> () {
                public void changed(ObservableValue<? extends Boolean> 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);
            }
        }
    }
查看更多
Bombasti
4楼-- · 2019-01-10 15:58

Here is a complete working example showing how to keep the model in sync with the view.....

package org.pauquette.example;

import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

public class CheckBoxExample extends Application {
    class BooleanCell extends TableCell<TableData, Boolean> {
        private CheckBox checkBox;

        public BooleanCell() {
            checkBox = new CheckBox();
            checkBox.setDisable(true);
            checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
                public void changed(ObservableValue<? extends Boolean> 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 cancelEdit() {
            super.cancelEdit();
            checkBox.setDisable(true);
        }

        public void commitEdit(Boolean value) {
            super.commitEdit(value);

            checkBox.setDisable(true);
        }

        @Override
        public void startEdit() {
            super.startEdit();
            if (isEmpty()) {
                return;
            }
            checkBox.setDisable(false);
            checkBox.requestFocus();
        }

        @Override
        public void updateItem(Boolean item, boolean empty) {
            super.updateItem(item, empty);
            if (!isEmpty()) {
                checkBox.setSelected(item);
            }
        }
    }

    // Pojo class. A Javabean
    public class TableData {
        SimpleBooleanProperty favorite;

        SimpleStringProperty stooge;

        // A javabean typically has a zero arg constructor
        // https://docs.oracle.com/javase/tutorial/javabeans/
        public TableData() {
        }

        // but can have others also
        public TableData(String stoogeIn, Boolean favoriteIn) {
            stooge = new SimpleStringProperty(stoogeIn);
            favorite = new SimpleBooleanProperty(favoriteIn);
        }

        /**
         * @return the stooge
         */
        public String getStooge() {
            return stooge.get();
        }

        /**
         * @return the favorite
         */
        public Boolean isFavorite() {
            return favorite.get();
        }

        /**
         * @param favorite
         *            the favorite to set
         */
        public void setFavorite(Boolean favorite) {
            this.favorite.setValue(favorite);
        }

        /**
         * @param stooge
         *            the stooge to set
         */
        public void setStooge(String stooge) {
            this.stooge.setValue(stooge);
        }
    }

    // Model class - The model in mvc
    // Typically a representation of a database or nosql source
    public class TableModel {
        ObservableList<TableData> stooges = FXCollections.observableArrayList();

        public TableModel() {
            stooges.add(new TableData("Larry", false));
            stooges.add(new TableData("Moe", true));
            stooges.add(new TableData("Curly", false));
        }

        public String displayModel() {
           StringBuilder sb=new StringBuilder();
           for (TableData stooge : stooges) {
               sb.append(stooge.getStooge() + "=" + stooge.isFavorite() + "|");
           }
           return sb.toString();
        }

        /**
         * @return the stooges
         */
        public ObservableList<TableData> getStooges() {
            return stooges;
        }

        public void updateStooge(TableData dataIn) {
            int index=stooges.indexOf(dataIn);
            stooges.set(index, dataIn);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

    private TableModel model;

    private TableModel getModel() {
        if (model == null) {
            model = new TableModel();
        }
        return model;

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        final VBox view=new VBox(10);
        final TableView<TableData> table = new TableView<>();
        final ObservableList<TableColumn<TableData, ?>> columns = table.getColumns();
        final TableModel model = getModel();

        final TableColumn<TableData, String> stoogeColumn = new TableColumn<>("Stooge");
        stoogeColumn.setCellValueFactory(new PropertyValueFactory<>("stooge"));
        columns.add(stoogeColumn);

        final Button showModelButton = new Button("Show me the Model, woo,woo,woo");
        final Label showModelLabel = new Label("Model?  Whats that?");
        showModelButton.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent event) {
                    showModelLabel.setText(model.displayModel());
                }});


        final TableColumn<TableData, CheckBox> favoriteColumn = new TableColumn<TableData, CheckBox>("Favorite");
        favoriteColumn.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<TableData, CheckBox>, ObservableValue<CheckBox>>() {

                    @Override
                    public ObservableValue<CheckBox> call(TableColumn.CellDataFeatures<TableData, CheckBox> arg0) {
                        TableData data = arg0.getValue();
                        CheckBox checkBox = new CheckBox();
                        checkBox.selectedProperty().setValue(data.isFavorite());
                        checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
                            public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val,
                                    Boolean new_val) {
                                data.setFavorite(new_val);
                                checkBox.setSelected(new_val);
                                model.updateStooge(data);
                            }
                        });

                        return new SimpleObjectProperty<CheckBox>(checkBox);
                    }

                });
        columns.add(favoriteColumn);
        table.setItems(model.getStooges());
        HBox hbox = new HBox(10);
        hbox.getChildren().addAll(showModelButton,showModelLabel);
        view.getChildren().add(hbox);
        view.getChildren().add(table);

        Scene scene = new Scene(view, 640, 380);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

}
查看更多
不美不萌又怎样
5楼-- · 2019-01-10 15:59

The simplest solution in order to have an EDITABLE checkbox linked to the model is:

Assuming that you have a Person model class with two fields, a "name" string and the "selected" boolean value:

public class Person {
    private final SimpleBooleanProperty selected;
    private final SimpleStringProperty name;

    public Person(String name) {
        this.selected = new SimpleBooleanProperty(false);
        this.name = new SimpleStringProperty(name);
    }

    public boolean isSelected() {
        return selected.get();
    }

    public SimpleBooleanProperty selectedProperty() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected.set(selected);
    }

    public String getName() {
        return name.get();
    }

    public SimpleStringProperty nameProperty() {
        return name;
    }

    public void setName(String name) {
        this.name.set(name);
    }
}

All you have to do in the controller is:

@FXML private TableColumn<Person, Boolean> checkBoxCol;
@FXML private TableColumn<Person, String> nameCol;

@Override
public void initialize(URL location, ResourceBundle resources) {
    checkBoxCol.setCellFactory(
        CheckBoxTableCell.forTableColumn(checkBoxCol)
    );
    checkBoxCol.setCellValueFactory(
            new PropertyValueFactory<>("selected")
    );
    nameCol.setCellValueFactory(
            new PropertyValueFactory<>("name")
    );
}
查看更多
Anthone
6楼-- · 2019-01-10 16:00
TableColumn select = new TableColumn("CheckBox");
        select.setMinWidth(200);
        select.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, CheckBox>, ObservableValue<CheckBox>>() {

            @Override
            public ObservableValue<CheckBox> call(
                    TableColumn.CellDataFeatures<Person, CheckBox> arg0) {
                Person user = arg0.getValue();

                CheckBox checkBox = new CheckBox();

                checkBox.selectedProperty().setValue(user.isSelected());



                checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
                    public void changed(ObservableValue<? extends Boolean> ov,
                            Boolean old_val, Boolean new_val) {

                        user.setSelected(new_val);

                    }
                });

                return new SimpleObjectProperty<CheckBox>(checkBox);

            }

        });
        table.getColumns().addAll( select);
查看更多
淡お忘
7楼-- · 2019-01-10 16:03

Small and simple.

row.setCellValueFactory(c -> new SimpleBooleanProperty(c.getValue().getIsDefault()));
row.setCellFactory(tc -> new CheckBoxTableCell<>());

查看更多
登录 后发表回答