JavaFX Checkbox

0

Javafx Checkbox tutorial:

JavaFX Checkbox UI control in which user can select using checkmark with one or more options.

Constructors of checkbox:

  • CheckBox()
    Creates a check box with an empty string for its label.
  • CheckBox(String text)
    Creates a check box with the specified text as its label.

Example using check box :


package javafxtuts;


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


/**
 *
 * @author javafxtuts
 */
public class Javafxtuts extends Application {
    
    

  

  @Override
  public void start(Stage primaryStage) {
      
      // setting title of application
      primaryStage.setTitle("javafxtuts.com");
      //Vbox layout
      VBox root = new VBox();
      
      Label lb =new Label("Select language You Know :");
      //to set space for label from other nodes of VBox
      lb.setPadding(new Insets(10));
    //creating new checkboxs. 
      CheckBox cb1 = new CheckBox("  C  ");
      CheckBox cb2 = new CheckBox("  Java  ");
       CheckBox cb3 = new CheckBox("  JavaFX  ");
      
            
      //pre select a check Box
      cb2.setSelected(true);
      
      // to set space for root
      root.setPadding(new Insets(10));
      
      //add all children of Vbox layout(root)
      root.getChildren().addAll(lb,cb1,cb2,cb3);
      
      Scene scene = new Scene(root, 400, 300);
      primaryStage.setScene(scene);
      primaryStage.show();
  }

  

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Output :

Explanation of check box example :

    • Create a VBox Layout

VBox root=new VBox();

    • Create a Label AS

Label lb =new Label();

    • Set space or padding using setPadding() method

cb2.setPadding(10);

    • Which set the space of 10 for cb2 in all directions.
    • To Pre selected a checkbox we use a method setSelected()

cb2.setSelected(true);

  • It mark the cb2 checkbox when application execute.
  • And finally add all children of root to the root using addAll() method.
Share.

Leave A Reply