JavaFX ToggleButton Tutorial with Examples

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- JavaFX ToggleButton

ToggleButton is a Button with 2 states including selected or deselected.
The ToggleButtons can be placed in a group (Toggle Group), the ToggleButtons in the same group at any one time at most only one button is selected, if a button is selected, the other nodes in the group will be deselected.

2- ToggleButton example


package org.o7planning.javafx.togglebutton;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ToggleButtonDemo extends Application {

   public void start(Stage stage) {

       // Hbox layout
       HBox root = new HBox();
       root.setPadding(new Insets(10));

       // Gender
       root.getChildren().add(new Label("Your gender:"));

       // Creating a ToggleGroup
       ToggleGroup group = new ToggleGroup();

       // Creating new Toggle buttons.
       ToggleButton maleButton = new ToggleButton("Male");
       ToggleButton femaleButton = new ToggleButton("Female");

       // Set toggle group
       // In a group, maximum only one button is selected

       maleButton.setUserData("I am a Male");
       femaleButton.setUserData("I am a Female");


       root.getChildren().addAll(maleButton, femaleButton);

       Scene scene = new Scene(root, 450, 300);

       stage.setTitle("ToggleButton (o7planning.org)");

   public static void main(String[] args) {


View more Tutorials: