JavaFX ChoiceBox Example

In this JavaFX source code example, we will see how to use the JavaFX ChoiceBox control with an example.

ChoiceBox is used for presenting the user with a small set of predefined choices. When the user clicks on the box, a list of choices is shown. Only one option can be selected at a time. When this list is not showing, the currently selected choice is shown. 

ChoiceBox item selection is handled by a SelectionModel.

JavaFX ChoiceBox Example

In our example, we have a choice box and a label. The choice box contains a list of strings. The selected item from the choice box is displayed in the label.
package sample;

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.control.SingleSelectionModel;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        initUI(stage);
    }

    private void initUI(Stage stage) {

        var root = new VBox(35);
        root.setPadding(new Insets(10));

        var lbl = new Label();

        var chbox = new ChoiceBox<>(FXCollections.observableArrayList(
                "First", "Second", "Third", "Fourth", "Fifth"));

        SingleSelectionModel<String> model = chbox.getSelectionModel();
        model.selectedItemProperty().addListener((observableValue, s, t1) -> lbl.setText(t1));

        root.getChildren().addAll(chbox, lbl);

        var scene = new Scene(root, 300, 250);

        stage.setTitle("ChoiceBox");
        stage.setScene(scene);
        stage.show();
    }

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


Comments