ChoiceBox
A ChoiceBox is a dropdown list that lets the user select one option from a list.
Example:
Select language → Java / Python / C++
👉 Only one value can be selected at a time.
1️⃣ FXML: ChoiceBox with Label
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="15" alignment="CENTER" xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.ChoiceBoxController">
<Label text="Select your favorite fruit:"/>
<ChoiceBox fx:id="fruitChoiceBox" onAction="#handleChoiceBoxAction"/>
<Label fx:id="selectionLabel" text="Your selection will appear here."/>
</VBox>
Explanation:
fx:id="fruitChoiceBox"→ lets the controller access the ChoiceBox.onAction="#handleChoiceBoxAction"→ calls a method whenever the selection changes.selectionLabel→ shows the currently selected value.
2️⃣ Controller: Populate and Handle ChoiceBox
package com.example;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
public class ChoiceBoxController {
@FXML
private ChoiceBox<String> fruitChoiceBox;
@FXML
private Label selectionLabel;
// Initialize method is called automatically after FXML loads
@FXML
private void initialize() {
// Populate ChoiceBox items
fruitChoiceBox.setItems(FXCollections.observableArrayList(
"Apple", "Banana", "Orange", "Mango", "Grapes"
));
// Set default value
fruitChoiceBox.setValue("Apple");
// Show default value in label
selectionLabel.setText("Default selection: " + fruitChoiceBox.getValue());
}
// Called when user changes selection
@FXML
private void handleChoiceBoxAction() {
String selectedFruit = fruitChoiceBox.getValue();
selectionLabel.setText("You selected: " + selectedFruit);
}
}
Explanation:
initialize()→ populate items and set a default value.getValue()→ get the currently selected item.handleChoiceBoxAction()→ dynamically updates theselectionLabel.
3️⃣ Main Class: Load FXML
package com.example;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("choicebox_layout.fxml"));
Scene scene = new Scene(loader.load(), 350, 200);
stage.setScene(scene);
stage.setTitle("ChoiceBox Example");
stage.show();
}
public static void main(String[] args) {
launch();
}
}
✅ Extra Notes for Learning ChoiceBox:
- Single selection only – if you need multiple selections, use
ListVieworComboBoxwith editable option. - Default value is optional – if not set, the ChoiceBox is empty initially.
- Dynamic reactions – you can trigger any code in
handleChoiceBoxAction()like changing colors, updating other UI elements, or even enabling buttons.