M. Barabas
M. Barabas

Reputation: 99

How to bind checkbox to variable in JavaFX?

I have controller class like this

public class Controller{
  private final Model model;

  @FXML
  private CheckBox chbx1;
  @FXML
  private CheckBox chbx2;
  @FXML
  private CheckBox chbx3;

  public Controller(Model model) {
       this.model = model;
   }

  @FXML
  private void initialize(){
     chbx1.selectedProperty().bind(model.initProperty());
  }
}

My model class look like this

public class Model{
   private final BooleanProperty init = new SimpleBooleanProperty(false);

   public BooleanProperty initProperty() {
      return init;
   }

   public final Boolean getInit() {
      return initProperty().get();
   }

   public final void setInit(Boolean init) {
      initProperty().set(init);
   }
}

I want to bind CheckBox to variable in Model. I am currently doing this, but I am getting CheckBox.selected : A bound value cannot be set. Error.

The second thing I wanna do is to check, which checkbox was selected or disselected and according to this set boolean variable in model. Is there some way how to do this ?

Upvotes: 0

Views: 5889

Answers (1)

fabian
fabian

Reputation: 82461

If the user clicks on a CheckBox, the control will attempt to modify the selectedproperty which will fail for a property that is (uni-directionally) bound.

You could do a bidirectional binding (if you modify the model an the change should result in a change in the ui):

chbx1.selectedProperty().bindBidirectional(model.initProperty());

if the model can only be modified by the controller, you also use a conventional binding, but the binding needs to be done the other way round:

model.initProperty().bind(chbx1.selectedProperty());

Upvotes: 2

Related Questions