How to add CheckBox's to a TableView in JavaFX

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

    There is a very simple way of doing this, you don't need to modify your model class with SimpleBooleanProperty or whatever, just follow these steps:

    1 - Suppose you have a "Person" object with a isUnemployed method:

    public class Person {
        private String name;
        private Boolean unemployed;
    
        public String getName(){return this.name;}
        public void setName(String name){this.name = name;}
        public Boolean isUnemployed(){return this.unemployed;}
        public void setUnemployed(Boolean unemployed){this.unemployed = unemployed;}
    }
    

    2 - Create the callback class

    import javafx.beans.property.SimpleObjectProperty;
    import javafx.beans.value.ObservableValue;
    import javafx.scene.control.CheckBox;
    import javafx.scene.control.TableColumn;
    import javafx.util.Callback;
    
    public class PersonUnemployedValueFactory implements Callback, ObservableValue> {
        @Override
        public ObservableValue call(TableColumn.CellDataFeatures param) {
            Person person = param.getValue();
            CheckBox checkBox = new CheckBox();
            checkBox.selectedProperty().setValue(person.isUnemployed());
            checkBox.selectedProperty().addListener((ov, old_val, new_val) -> {
                person.setUnemployed(new_val);
            });
            return new SimpleObjectProperty<>(checkBox);
        }
    }
    

    3 - Bind the callback to the table column

    If you use FXML, put the callback class inside your column:

    
        
            
                
                     
                
            
    
            ...
        
    
    

    Don't forget to import the class in your FXML:

    
    

    Without FXML, do it like this:

    TableColumn column = (TableColumn) personTable.getColumns().get(0);
    column.setCellValueFactory(new PersonUnemployedValueFactory());
    

    4 - That's it

    Everything should work as expected, with the value being set to the backing bean when you click on the checkbox, and the checkbox value correctly being set when you load the items list in your table.

提交回复
热议问题