I want a group of ToggleButon
to behave as a group of RadioButton
, meaning that there is always an option selected. I do not know if there is any method that does it directly or, on the contrary, I have to program it.
I want a group of ToggleButon
to behave as a group of RadioButton
, meaning that there is always an option selected. I do not know if there is any method that does it directly or, on the contrary, I have to program it.
You have two ways of doing it: either you create a group of RadioButton
and tune them with CSS or you intercept the attempt to leave the ToggleButton
deselected and modify them according to your convenience.
The easy way is the second. Here is a small example:
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ToggleSiempreSeleccionado extends Application {
@Override
public void start(Stage primaryStage) {
ToggleButton Opción1 = new ToggleButton("Opción 1");
ToggleButton Opción2 = new ToggleButton("Opción 2");
ToggleGroup grupoOpciones = new ToggleGroup();
grupoOpciones.getToggles().addAll(Opción1, Opción2);
HBox contenedorRaíz = new HBox();
contenedorRaíz.getChildren().addAll(Opción1, Opción2);
contenedorRaíz.setPadding(new Insets(10,10,10,10));
contenedorRaíz.setSpacing(10);
Scene escena = new Scene(contenedorRaíz, 180, 50);
primaryStage.setScene(escena);
primaryStage.show();
grupoOpciones.selectedToggleProperty().addListener(
(ObservableValue<? extends Toggle> arg0, Toggle valorAnterior, Toggle valorNuevo) -> {
if (grupoOpciones.getToggles().indexOf(grupoOpciones.getSelectedToggle()) == -1) {
grupoOpciones.selectToggle(valorAnterior);
}
}
);
}
public static void main(String[] args) {
launch(args);
}
}