13.21 Ui Thread

We continue with our JavaFX event handling and this time we add a CheckBox to the UI. We place it just below the existing Button, inside the GridPane, with a row and column index so it appears in the right cell of the grid:

<CheckBox fx:id="checkBox" text="Check" GridPane.rowIndex="2" GridPane.columnIndex="0"/>

You could attach an event handler that fires every time the box is toggled, but in most cases we do not really care about each click on a checkbox. What matters is its state at the moment we actually validate the form — typically when the user presses the OK button of a dialog or the Save button of a toolbar. So we keep the Button handler as the place where we read all the fields together.

Reading the checkbox in the Button handler

In the FXML we make sure the CheckBox has a stable fx:id so the controller can reference it, and we keep the existing onAction attribute on the Button that calls the handler. In the controller we declare the CheckBox as an @FXML field with the same name as the fx:id and we extend the existing method:

@FXML private CheckBox checkBox;
@FXML private TextField nameField;

@FXML
public void sayHello() {
  if (checkBox.isSelected()) {
    System.out.println("Bonjour " + nameField.getText());
  }
}

When we run the program with a name like "Alex" typed in the field, pressing the button only prints "Bonjour Alex" if the checkbox is checked. If we uncheck it and press the button again, nothing is printed: the handler reads the state of the checkbox on demand and skips the greeting. That is it for this video on combining a CheckBox with events — see you in the next one.