JavaFX: Putting Objects Into Choice Box

This entry is part 33 of 55 in the series JavaFX

We can add any kind of object we want to a choice box.

Here in our Rock class, the class consists of a firstname and a lastname variables.  To display the object correctly, we can use a toString method.

The choice box calls the toString method of each item to determine the text to display in the choice list.

As shown in line 72, we are able to print out a rock class simply because we have the toString method in the class.

package javafxapplication25;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.layout.Priority;

public class JavaFXApplication25 extends Application {

    class Rock {

        private final String firstName;
        private final String lastName;

        public Rock(String FirstName, String LastName) {
            firstName = FirstName;
            lastName = LastName;

        public String toString() {
            return firstName + " " + lastName;
    ChoiceBox<Rock> rock;

    public void start(Stage stage) {

        stage.setTitle("JavaFX Program!");

        rock = new ChoiceBox<Rock>();
        Rock rod = new Rock("Rod", "Stewart");
        Rock bruce = new Rock("Bruce", "Springsteen");
        Rock don = new Rock("Don", "Henley");


        HBox hboxPane = new HBox(10); // spacing = 10       
        hboxPane.setPadding(new Insets(10, 10, 10, 10));

        Label lb = new Label("Selection:");
        Button btn = new Button("OK");
        btn.setOnAction(e -> buttonClick());

        hboxPane.setHgrow(rock, Priority.ALWAYS);

        hboxPane.getChildren().addAll(lb, rock, btn);

        Scene scene = new Scene(hboxPane, 300, 200);
    private void buttonClick() {

        Rock rk = rock.getValue();

    public static void main(String[] args) {



Series Navigation<< JavaFX: Setting up a choice box
JavaFX: Creating a second stage to show alert >>