Search code examples
javafxcomboboxbox

Connecting two Choice Boxes or Combo Boxes


Is there a way to connect two Choice boxes or Combo boxes. It doesn't really matter which. I want to change the items in box two(Integers), depending on what's been chosen on box one(Strings).

ex:
Box one:
cupcakes
cookies

Box two:
if cupcakes, then the numbers 1,2,3, .... ,28,29,30.
if cookies, then the numbers 1,2,3, .... ,27,28.
else empty box.

The numbers can be put in through an array. What I have a problem with is how to use the event handler to change whats in the second box.


Solution

  • There can be different approaches depending on your requirements. One can be:

    @Override
    public void start( Stage stage )
    {
    
        final Map<String, ObservableList<Integer>> map = new HashMap<>();
        map.put( "cupcakes", FXCollections.observableArrayList( 1,2,3,4,5,6));
        map.put( "cookies",  FXCollections.observableArrayList(11,12,13,14,15,16));
    
        final ComboBox<String> comboOne = new ComboBox<>();
        comboOne.getItems().addAll(
                "cupcakes",
                "cookies",
                "empty box"
        );
        final ComboBox<Integer> comboTwo = new ComboBox<>();
    
        comboOne.getSelectionModel().selectedItemProperty().addListener( new ChangeListener<String>()
        {
            @Override
            public void changed( ObservableValue<? extends String> observable, String oldValue, String newValue )
            {
                comboTwo.setItems( 
                        map.containsKey( newValue ) ? map.get( newValue ) : FXCollections.emptyObservableList()
                );
            }
        } );
    
        VBox grid = new VBox( 20 );
        grid.getChildren().addAll( comboOne, comboTwo );
    
        Scene scene = new Scene( grid, 450, 250 );
        stage.setScene( scene );
        stage.show();
    }