Issue
I am using a custom switch button from the answer CustomButton. As you can see in the constructor a click listener will be set to both button and the object itself. In the MainController class, I created an instance of it and set a mouse click event listener in order to update the UI depending on its state of it, but that led to a weird behavior where on some clicks the button toggles and changes color sometimes the UI will be updated...
This is how I am creating and adding click listener in MainController:
filterSwitchButton = new SwitchButton();
filterSwitchButton.setId("filterSwitchButton");
HBox.setMargin(filterSwitchButton, new Insets(0, 20, 0, 50));
filterSwitchButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
// update UI
}
});
How can I update the UI and change the state of the switch button when it is clicked?
Solution
This answer to a related earlier question:
exposes an on
property modeling the switch state.
The solution is similar to the updated answer by SephB.
If the developer wants to do something when the on
property state changes, they can listen to the on
property, rather than using event handlers on exposed internal nodes in the control. As many such property change listeners as desired can be added to the property.
Similarly, the on
property can be used to change the switch state, which will be reflected in the UI and the resultant change event will also be propagated to any defined listeners.
For example:
Switch lightSwitch = new Switch();
lightSwitch.onProperty().addListener((observable, wasOn, nowOn) -> {
System.out.println(nowOn ? "on" : "off");
});
lightSwitch.setOn(true);
Will print "on
".
Answered By - jewelsea
Answer Checked By - Willingham (JavaFixing Volunteer)