JavaFX ChoiceBox

0

JavaFX ChoiceBox tutorial:

JavaFX ChoiceBox is a UI control used to present small no. of predefined choice in drop-down list.

And allow user to select one choice.

Constructors of choice box:

  • ChoiceBox()Create a new ChoiceBox which has an empty list of items.
  • ChoiceBox(ObservableList items)Create a new ChoiceBox with the given set of items or a list of items.

methods of choice box:

    • We create an empty ChoiceBox AS

ChoiceBox cb =new ChoiceBox();

    • To set items to the choiceBox we use setItem() method AS
      cb.setItems(FXCollections.observableArrayList(“A”, “B”, “C”, “D”));
    • To set item at time of creating checkBox

ChoiceBox cb = new ChoiceBox(
FXCollections.observableArrayList(
"A", "B", "C"));

Example of choice box:


package javafxtuts;


import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
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 vb = new VBox();
      
      Label lb =new Label("Where do you live?");
      //to set space for label from other nodes of VBox
      lb.setPadding(new Insets(10));
    
      ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(" US ", " UK ", " India "," England "));
      // to set space for root
      vb.setPadding(new Insets(10));
      
      //add all children of Vbox layout(root)
      vb.getChildren().addAll(lb,cb);
      Scene scene = new Scene(vb, 400, 300);
      primaryStage.setScene(scene);
      primaryStage.show();
  }

  

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

Output :

Explanation of choice box example :

import javafx.collections.FXCollections;

    • For FxCollection which is nested class of collections.

import javafx.scene.control.ChoiceBox;

  • For ChoiceBox
  • setPadding() to set padging for lb.
  • Creating ChoiceBox with a list of item AS
ChoiceBox cb = new ChoiceBox(
FXCollections.observableArrayList(
" US ", " UK ", " India "," England "));
  • Here observableArrayList() method of class FXCollections is used to return an observableList().
  • Share.

    Leave A Reply