JavaFX: Which checkbox is checked

This entry is part 30 of 55 in the series JavaFX

In an event listener, you can test the state of a check box by using the isSelected method, and you can set the state of a check box by calling its setSelected method.

package javafxapplication24;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;

public class JavaFXApplication24 extends Application {

    CheckBox cb1 = new CheckBox("Rock");
    CheckBox cb2 = new CheckBox("Country");

    @Override
    public void start(Stage stage) {

        stage.setTitle("JavaFX Program!");

        VBox vbox_pane = new VBox();
        vbox_pane.setAlignment(Pos.CENTER);

        HBox hbox1 = new HBox();
        HBox hbox2 = new HBox();
        HBox hbox3 = new HBox();

        hbox1.setPadding(new Insets(15, 12, 15, 12));
        hbox1.setAlignment(Pos.CENTER_LEFT);

        hbox2.setPadding(new Insets(15, 12, 15, 12));
        hbox2.setAlignment(Pos.CENTER_LEFT);

        Button btn = new Button("Submit");
        
        cb2.setSelected(true);

        btn.setOnAction(e -> buttonClick());

        hbox1.getChildren().add(cb1);
        hbox2.getChildren().add(cb2);
        hbox3.getChildren().add(btn);

        vbox_pane.getChildren().addAll(hbox1, hbox2, btn);

        Scene scene = new Scene(vbox_pane, 300, 250);
        stage.setScene(scene);

        stage.show();
    }

    private void buttonClick() {

        if (cb1.isSelected()) {
            System.out.println("You like Rock music");
        }
        if (cb2.isSelected()) {
            System.out.println("You like Country music");
        }
    }

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

checkbox2

checkbox3

Series Navigation<< JavaFX: Creating checkboxes
JavaFX: Setting up radio button group >>