1

I'm having trouble getting the boolean value of whether a checkbox in a tableView for JavaFX is selected or not.

(Link to Image) https://i.stack.imgur.com/1xgik.png

For some reason the when I getCellObservableValue() to get the CheckBox at index 1, I get null as the result.

//From SceneBuilder/JavaFX file
<TableColumn fx:id="labelColumn" prefWidth="112.57145690917969" text="Use 
as Label" />


//Setting Up Table, which displays everything correctly 
TableColumn<Integer,CheckBox>  labelColumn = (TableColumn<Integer, 
CheckBox>) elements.get("labelColumn");
labelColumn.setCellFactory(data -> new CheckBoxTableCell<>());
monitorTable.setEditable(true);



//Trying to Access, which gives null pointer exception
CheckBox cb = (CheckBox) labelColumn.getCellObservableValue(1);
System.out.println(cb.isSelected());
  • I am going to guess you need `setCellFactory`. https://stackoverflow.com/questions/7217625/how-to-add-checkboxs-to-a-tableview-in-javafx – SedJ601 Jul 11 '19 at 20:34
  • I posted [an answer](https://stackoverflow.com/questions/53361763/javafx-tableview-checkbox-requires-focus/53362472#53362472) on a similar question that might help as well. – Zephyr Jul 11 '19 at 23:47

1 Answers1

3

That method returns null if there's no cellValueFactory set. Besides, you should really have a model to hold this state—a TableView is just a view. Unlike the TableViewSelectionModel, which represents which items are selected solely in the context of the TableView itself, a column containing CheckBoxes represents the "boolean state" of a property of the model. For example:

public class ToDoTask {

    private final StringProperty name = new SimpleStringProperty(this, "name");
    private final BooleanProperty complete = new SimpleBooleanProperty(this, "complete");

    // constructors, getters, setters, and property-getters omitted for brevity
}

A TableView for displaying that class could be configured like the following:

TableView<ToDoTask> table = new TableView<>();
table.setItems(...);

TableColumn<ToDoTask, String> nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(features -> features.getValue().nameProperty());
table.getColumns().add(nameCol);

TableColumn<ToDoTask, Boolean> completeCol = new TableColumn<>("Complete");
completeCol.setCellValueFactory(features -> features.getValue().completeProperty());
completeCol.setCellFactory(CheckBoxTableCell.forTableColumn(completeCol));
table.getColumns().add(completeCol);

You would then query if a task is complete by accessing the model:

table.getItems().get(...).isComplete();

Another option to setting the cellValueFactory is to register a Callback with the CheckBoxTableCells themselves. See CheckBoxTableCell#forTableColumn(Callback).


Also, note that getCellObservableValue() returns an ObservableValue. A CheckBox is not an ObservableValue. If you weren't receiving null you'd be getting a ClassCastException.

Slaw
  • 37,820
  • 8
  • 53
  • 80