eniniz
eniniz

Reputation: 37

How to populate a tableview that contain CheckBox in JavaFX

I created a TableView that I populated with an ObservableList, Some column of my table are CheckBox and I want is that the CheckBox bind with the model object that I had created. Until now the result that I get is: If it's text I can see the result but if it is CheckBox is always unchecked

Upvotes: 0

Views: 5745

Answers (1)

Jens-Peter Haack
Jens-Peter Haack

Reputation: 1907

Exampla of a checkbox in a tableview:

  1. The item shown in the table: Member

    public class Member {
        private StringProperty myName;
        private BooleanProperty myCheck;
    
        public Member(String name, boolean checked) {
            myName = new SimpleStringProperty(name);
            myCheck = new SimpleBooleanProperty(checked);
        }
    
        public StringProperty nameProperty() { return myName; }    
        public BooleanProperty checkProperty() { return myCheck; }
    }
    
  2. The Table: (Now using the built in class CheckBoxTableCell, thanks to James.D)

    ObservableList<Member> members = FXCollections.observableArrayList();
    
    members.add(new Member("peter", true));
    members.add(new Member("gernot", true));
    members.add(new Member("fritz", false));
    for (int i = 1000; i < 2000; i++) members.add(new Member("N"+i, (i%5==0)));
    
    TableView<Member> table = new TableView<Member>();
    table.prefHeightProperty().bind(box.heightProperty());
    table.setItems(members);
    
    TableColumn<Member,String> c1 = new TableColumn<Member,String>("Name");
    c1.setCellValueFactory(new PropertyValueFactory<Member,String>("name"));
    table.getColumns().add(c1);
    
    TableColumn<Member,Boolean> c2 = new TableColumn<Member,Boolean>("Membership");
    c2.setCellValueFactory(new PropertyValueFactory<Member,Boolean>("check"));
    c2.setCellFactory(column -> new CheckBoxTableCell()); 
    table.getColumns().add(c2);
    
    pane.getChildren().addAll(table);
    
  3. Result:

enter image description here

Upvotes: 2

Related Questions