JavaFX Tutorial - Java ChoiceBox(ObservableList < T > items) Constructor








Syntax

ChoiceBox(ObservableList < T > items) constructor from ChoiceBox has the following syntax.

public ChoiceBox(ObservableList < T > items)

Example

In the following code shows how to use ChoiceBox.ChoiceBox(ObservableList < T > items) constructor.

//from   w w  w .  j ava 2 s .co  m

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setScene(scene);
        stage.show();

        stage.setWidth(300);
        stage.setHeight(200);

        final String[] greetings = new String[]{"Hello", "Hola", "1","2"};
        final ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList("1","2","3","4"));
        cb.getSelectionModel().selectedIndexProperty().addListener(new
            ChangeListener<Number>() {
                public void changed(ObservableValue ov,
                    Number value, Number new_value) {
                        System.out.println(new_value.intValue());
            }
        });

        cb.setValue("2");
        HBox hb = new HBox();
        hb.getChildren().addAll(cb);
        hb.setSpacing(30);
        hb.setAlignment(Pos.CENTER);
        hb.setPadding(new Insets(10, 0, 0, 10));

        ((Group) scene.getRoot()).getChildren().add(hb);
        
    }
}