In this Java GUI article we are going to talk about Creating ChoiceBox in JavaFX, according to
JavaFX Documentation the ChoiceBox is used for presenting the user with a relatively small
set of predefined choices from which they may choose. The ChoiceBox, when “showing”, will
display to the user these choices and allow them to pick exactly one choice. When not showing,
the current choice is displayed.
By default, the ChoiceBox has no item selected unless otherwise specified. although the
ChoiceBox will only allow a user to select from the predefined list.
Python GUI Development Tutorials with Video Training
- PyQt5 GUI Development Tutorials
- TKinter GUI Development Tutorials
- Pyside2 GUI Development Tutorials
- Kivy GUI Development Tutorials
- wxPython GUI Development Tutorials
You can create javafx choicebox by creating the object of ChoiceBox class.
1 |
ChoiceBox choiceBox = new ChoiceBox(); |
This is our HBox Layout, because we want to align our widget horizontally by this reason we
are using HBox container or layout. if you want to align vertically than you can use VBox layout.
1 |
HBox hbox = new HBox(); |
So now we need to add some items to our javafx choicebox.
1 2 3 |
choiceBox.getItems().add("Python"); choiceBox.getItems().add("Java"); choiceBox.getItems().add("C++"); |
When you create a widget in JavaFX, for example button,label,combobox or some other
widgets, you need to add that to your container, in here we need to add our choice box
HBox container.
1 |
hbox.getChildren().add(choiceBox); |
Also for every JavaFX application we need to create a Scene object. in the scene we need
to add our container with the width and height of the window, if you want to colorize your
window, you can do it in here. you can see that we have given 300 width and 200 height for the
window.
1 |
Scene scene = new Scene(hbox, 300, 200); |
At the end you need to set your scene object to the stage of the window, and show the window.
1 2 |
stage.setScene(scene); stage.show(); |
Run the complete code and this is the result.
Subscribe and Get Free Video Courses & Articles in your Email