Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a toggle group from not having a toggle selected - Java FX

I have a toggle group with two toggle buttons that should look like this (Yellow toggle is the selected toggle).

enter image description here

However when I click on the selected toggle both toggles become unselected and look like this.

enter image description here

Then if I try to get whether the toggle is selected, I get a nullPointerException.

(Boolean) toggleGroup.getSelectedToggle().getUserData();

Is it possible to prevent the selected toggle from being unselected when it is clicked?

like image 998
joshLor Avatar asked Oct 19 '17 16:10

joshLor


1 Answers

This one works for me. If the new selected element is null that means theres no selected element, therefore just select the previous one (which is the "oldValue")

toggleGroup.selectedToggleProperty().addListener((obsVal, oldVal, newVal) -> {
    if (newVal == null)
        oldVal.setSelected(true);
});
like image 152
Wesos de Queso Avatar answered Oct 10 '22 23:10

Wesos de Queso