JavaFX: Change listener for a Choice Box

This entry is part 35 of 55 in the series JavaFX

We have looked at choice box in our earlier posts.  A lot of the times, we would want an output that react immediately to a choice box selection.

JavaFX provides a change listener method called addListener.

We usually apply this method to a so called ObservableCollection which actually is a generic interface.

In our ChoiceBox example, you would have noticed that the choice box is defined as a generic Interface.

rock = new ChoiceBox<Rock>();

And in this case, we are passing a Rock item into ChoiceBox.  We could for example, pass a string item into ChoiceBox as in

rock = new ChoiceBox<String>();

Let’s use our earlier posts on ChoiceBox as an example.

package javafxapplication28;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
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 JavaFXApplication28 extends Application {

    class Rock {

        private final String firstName;
        private final String lastName;

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

        @Override
        public String toString() {
            return firstName + " " + lastName;
        }
    }

    ChoiceBox<Rock> rock;

    @Override
    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");

        rock.getItems().add(rod);
        rock.getItems().add(bruce);
        rock.getItems().add(don);
        rock.setValue(bruce);

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

        Label lb = new Label("Selection:");
        Label lb1 = new Label("Selected Item");

        rock.getSelectionModel().selectedItemProperty().addListener((ObservableValue, oldValue, newValue) -> {
            lb1.setText(newValue.toString());
        });

        hboxPane.setHgrow(rock, Priority.ALWAYS);

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

        Scene scene = new Scene(hboxPane, 500, 400);
        stage.setScene(scene);

        stage.show();
    }

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

So now if we just make a selection to Don Henley, we will have an immediate output as shown in the screenshot below:

listener

Series Navigation<< JavaFX: Creating a second stage to show alert
JavaFX: Setting up list view >>