How to create a JavaFX Choice Box

JavaFX Choice Box is a nice control which helps in selecting a choice from group of options. It is quite similar to select input used in Html. Clicking on a choice displays a list of items as a dropdown.

ChoiceBox class is used to create a Choice Box

ChoiceBox choice1 = new ChoiceBox(FXCollections.observableArrayList(
"Rose", "Daisy", "Lily")
);

or

ChoiceBox choice2 = new ChoiceBox();
choice2.setItems(FXCollections.observableArrayList(
"Rose", "Daisy", "Lily")
);

Let’s add a choice box to JavaFX Scene:

package javafxcontrols;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class JavaFxControls extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        ChoiceBox choice1 = new ChoiceBox(FXCollections.observableArrayList(
                "Rose", "Daisy", "Lily")
        );
        
        HBox hbox = new HBox(choice1);
        Scene scene = new Scene(hbox, 200, 150);
        primaryStage.setScene(scene);
        primaryStage.setTitle("A Choice Box");
        primaryStage.show();

    }

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

}

output:

javafx choice box

Separate items with a separator

new Separator()

ChoiceBox choice2 = new ChoiceBox();
choice2.setItems(FXCollections.observableArrayList(
"Rose", "Daisy", "Lily", new Separator(), "Parrot", "Goose", "KingFisher")
);

package javafxcontrols;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Separator;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class JavaFxControls extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        ChoiceBox choice2 = new ChoiceBox();
        choice2.setItems(FXCollections.observableArrayList(
                "Rose", "Daisy", "Lily", new Separator(), "Parrot", "Goose", "KingFisher")
        );

        HBox hbox = new HBox(choice2);
        Scene scene = new Scene(hbox, 200, 250);
        primaryStage.setScene(scene);
        primaryStage.setTitle("A Choice Box");
        primaryStage.show();

    }

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

}

output:

javafx choice box separator

you can also show tooltip on choice box using setTooltip() method

choice.setTooltip(new Tooltip("Select a option"));

Leave a Reply

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