How to create a JavaFX Checkbox

JavaFX CheckBox is a special control that looks like a square box, can be used to select a option. when a CheckBox is selected a tick mark appears inside the square. Multiple CheckBoxes can be created for list of options.

A CheckBox can be selected by default using setSelected() method to true

Create a CheckBox:

CheckBox check1 = new CheckBox();
check1.setText("Checkbox 1");

or

CheckBox check2 = new CheckBox("Checkbox 2");

Let’s create multiple CheckBoxes:

package javafxcontrols;

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

public class JavaFxControls extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        
        CheckBox check1 = new CheckBox("checkbox 1");
        CheckBox check2 = new CheckBox("checkbox 2");
        check2.setSelected(true);
        CheckBox check3 = new CheckBox("checkbox 3");
       
        VBox vbox = new VBox(10, check1, check2, check3);
        vbox.setPadding(new Insets(20, 0, 0, 20));

        Scene scene = new Scene(vbox, 200, 150);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Creating Checkbox");
        primaryStage.show();

    }

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

}

output:

javafx checkbox

Leave a Reply

Your email address will not be published. Required fields are marked *