Search code examples
bindingjavafxproperty-binding

How to make this JavaFX binding smarter?


I have 3 ToggleButtons and a GridPane containing 3 cells.

Case 1: Only 1 ToggleButton is selected, corresponding GridPane cell is expected to fill whole pane.

Case 2: 2 of the ToggleButtons are selected, corresponding 2 GridPane cells is expected to fill whole pane with equally. (And the same logic when 3 ToggleButtons are selected of course.)

Currently, I am already achieved my goal with the following implementation but what I want to learn is make this smarter. With the word smarter, I mean implementing something shorter that transforms ToggleButton state to a double value (deselected => 0 , selected=> 100). I don't want to implement those by repeating if clauses, but I am trying to implement something that can be attached before .bind() method call.

Current implementation for one ToggleButton is as following:

myToggleButton.selectedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if(newValue){
                myGridPane.getColumnConstraints().get(0).setPercentWidth(100);
            }else{
                myGridPane.getColumnConstraints().get(0).setPercentWidth(0);
            }
        }
    });

Solution

  • Yes you can, try the following for binding PercentWidth

    ObservableBooleanValue condition = myToggleButton.selectedProperty();
    NumberBinding number = Bindings.when(condition).then(100).otherwise(0);
    myGridPane.getColumnConstraints().get(0).percentWidthProperty.bind(number);