JavaFX: Creating checkboxes

This entry is part 29 of 55 in the series JavaFX

Checkboxes allow multiple selections.  Here in this post, we also look at how to put 2 Hboxes into a Vbox where each Hbox is for one Checkbox.

Creating a checkbox is relatively easy.

CheckBox cb1 = new CheckBox("Rock");

Consider the the example below.

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.CheckBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;
 
public class JavaFXApplication24 extends Application {
 
    @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();
        
        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);
 
        CheckBox cb1 = new CheckBox("Rock");
        CheckBox cb2 = new CheckBox("Country");
 
        hbox1.getChildren().add(cb1);   
        hbox2.getChildren().add(cb2);  
        
        vbox_pane.getChildren().addAll(hbox1,hbox2);
 
        Scene scene = new Scene(vbox_pane, 300, 250);
        stage.setScene(scene);
 
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

checkbox

Series Navigation<< JavaFX: The setText() method
JavaFX: Which checkbox is checked >>

Leave a comment

Leave a Reply