JavaFX CheckBox selection

JavaFx User Interface Components: Exercise-10 with Solution

Write a JavaFX application with multiple CheckBox options (e.g., "Red," "Green"). Display a label showing the selected options when checkboxes are clicked.

Sample Solution:

JavaFx Code:


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {

    public void start(Stage primaryStage) {
        primaryStage.setTitle("CheckBox Selection App");

        // Create a label to display the selected options.
        Label selectionLabel = new Label("Selected Options: ");

        // Create CheckBox options.
        CheckBox redCheckBox = new CheckBox("Red");
        CheckBox greenCheckBox = new CheckBox("Green");
        CheckBox blueCheckBox = new CheckBox("Blue");
        CheckBox yellowCheckBox = new CheckBox("Yellow");

        // Handle the action when a CheckBox is clicked.
        redCheckBox.setOnAction(event -> updateSelectionLabel(selectionLabel, redCheckBox));
        greenCheckBox.setOnAction(event -> updateSelectionLabel(selectionLabel, greenCheckBox));
        blueCheckBox.setOnAction(event -> updateSelectionLabel(selectionLabel, blueCheckBox));
        yellowCheckBox.setOnAction(event -> updateSelectionLabel(selectionLabel, yellowCheckBox));

        // Create a layout (VBox) to arrange the CheckBox options and label.
        VBox root = new VBox(10);
        root.getChildren().addAll(redCheckBox, greenCheckBox, blueCheckBox, yellowCheckBox, selectionLabel);

        // Create the scene and set it in the stage.
        Scene scene = new Scene(root, 300, 200);

        // Set the title of the window.

    // Update the label to display the selected options.
    private void updateSelectionLabel(Label label, CheckBox checkBox) {
        StringBuilder selectedOptions = new StringBuilder("Selected Options: ");
        if (checkBox.isSelected()) {
            selectedOptions.append(checkBox.getText()).append(", ");

In the above JavaFX application, we use CheckBox options, and when a CheckBox is clicked, the label displays the selected options. The elements are organized using a 'VBox'.

Sample Output:

JavaFx: JavaFX CheckBox selection.
JavaFx: JavaFX CheckBox selection.


Flowchart: JavaFX CheckBox selection.
Flowchart: JavaFX CheckBox selection.

Java Code Editor:

Previous: JavaFX Country selection application.
Next: JavaFX preference form using RadioButton.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.