How to create a JavaFX Toggle Button

JavaFX Toggle Button is somewhat similar to JavaFX Radio Button. In fact, RadioButton class is a specialized implementation of the ToggleButton class. If a radio button in a group is already clicked, we can’t unselect the whole group. Whereas in toggle buttons group, only one button at a time can be selected, or whole group can be unselected.

Create a Toggle Button:

ToggleButton toggle1 = new ToggleButton();

or

ToggleButton toggle2 = new ToggleButton("Toggle Button with text");

or

Image image = new Image(getClass().getResourceAsStream("image.png"));
ToggleButton toggle3 = new ToggleButton ("Toggle Button with a image", new ImageView(image));

Let’s create a single Toggle Button without group

package javafxcontrols;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFxControls extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        
        ToggleButton toggle2 = new ToggleButton("Toggle Button with text");
        
        VBox vbox = new VBox(5, toggle2);
        Scene scene = new Scene(vbox, 300, 100);
        primaryStage.setScene(scene);
        primaryStage.setTitle("A Toggle Button");
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }

}

output:

toggle button

Toggle buttons in a group:

package javafxcontrols;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFxControls extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        
        final ToggleGroup group = new ToggleGroup();
        
        ToggleButton toggle1 = new ToggleButton("Toggle 1");
        toggle1.setToggleGroup(group);
        
        ToggleButton toggle2 = new ToggleButton("Toggle 2");
        toggle2.setToggleGroup(group);
        
        ToggleButton toggle3 = new ToggleButton("Toggle 3");
        toggle3.setToggleGroup(group);
        
        ToggleButton toggle4 = new ToggleButton("Toggle 4");
        toggle4.setToggleGroup(group);
        
        HBox hbox = new HBox(5, toggle1, toggle2, toggle3, toggle4);
        StackPane stack = new StackPane(hbox);
        Scene scene = new Scene(stack);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Toggle Buttons in a group");
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }

}

output:

javaFX toggle button group