FreeCode

Donate HTML/CSS JavaFX Java Home
JavaFX Starter Template JavaFX Labels JavaFX Buttons JavaFX Toggle Buttons JavaFX Radio Buttons and Toggle Groups JavaFX Checkboxes JavaFX Choice Boxes JavaFX Combo Boxes JavaFX Text Areas JavaFX Text Fields JavaFX List Views JavaFX Image Views JavaFX Color Pickers JavaFX Date Pickers JavaFX Resizable Split Pane Layouts JavaFX VBox (Vertical Box Layouts) JavaFX HBox (Horizontal Box Layouts) JavaFX Flow Pane Layouts JavaFX Tile Pane Layouts JavaFX Web Views

JavaFX Choice Boxes

Code Description:

How a Choice Box Works

The code provided below shows how to create a Choice Box in JavaFX. Choice Boxes allow for a drop down of multiple options that you can select from. Do note that Choice Boxes are only meant for a small number of items (typically 10 items or less). If you require more items, consider using a Combo Box. The runnable example code shows how the selected value can be retrieved. After retrieved in the example, we display the value in a label.

Creating a Choice Box

To make a new Choice Box, we need to first create an Array or List like data structure. We can then create a new Choice Box object where we specify the data type it will use. In this case we are using String. We can use the setItems() method to add the choices to the drop down. The setItems() method requires an ObservableList parameter so we can convert our Array or List to one. As it is an observable list, any items we add to that list will reflect in our Choice Box.

Choice Box Syntax:

String[] choices = {"Option 1", "Option 2", "Option 3"};
		
ChoiceBox<String> choiceBox = new ChoiceBox<String>();
choiceBox.setItems(FXCollections.observableArrayList(choices));

Runnable JavaFX Choice Box Example Code:

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Demo extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
		
        VBox root = new VBox();
		
	Label label = new Label();
		
	String[] choices = {"Option 1", "Option 2", "Option 3"};
		
	ChoiceBox<String> choiceBox = new ChoiceBox<String>();
	choiceBox.setItems(FXCollections.observableArrayList(choices));
		
	choiceBox.setValue(choices[0]);
	label.setText("Selected Value: " + choices[0]);
		
	choiceBox.setOnAction(new EventHandler<ActionEvent>() {
			
	    @Override
	    public void handle(ActionEvent event) {
	        label.setText("Selected Value: " + choiceBox.getValue());
	    }
	});
					
	root.getChildren().addAll(choiceBox, label);
		
	primaryStage.setTitle("Choice Box Demo");
	primaryStage.setScene(new Scene(root, 200, 100));
	primaryStage.show();
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Note: You will NOT be able to copy and paste this code into your IDE unless you first set up JavaFX for your project. Check out this link if you need help setting up JavaFX:

JavaFX Comprehensive Setup Guide

Output:

JavaFX Choice Box Output Image

Important Methods:

  • setValue() - Used to set the current choice value. You can use this to set the initial value since it will display as empty if not set.
  • getValue() - Used to get the currently selected value.
  • setItems() - Sets all of the possible choices that can be selected from the choice box.
  • getItems() - Returns a list of all items in the choice box.
  • isShowing() - Returns if the drop down box is being currently shown.
  • setDisable() - Used to make the choice box grayed out and unclickable. EX: "choiceBox.setDisable(true);"
  • setPrefSize() - Set the preferred width and height for the choice box.
  • setOnAction() - Set the code and event handler for when the choice box is clicked or pressed.
  • setStyle() - Set an inline CSS-like style on the choice box. EX: "choiceBox.setStyle("-fx-background-color: green;");"
  • setTooltip() - Set a message that displays when a user hovers over the choice box control for a certain amount of time. EX: "choiceBox.setTooltip(new Tooltip("Press Me"));"
  • setVisible() - Show or hide a choice box from the scene. EX: "choiceBox.setVisible(false);"

Related Links:

JavaFX Combo Boxes Array Data Structures Array List Data Structures Linked List Data Structures