mydomain
No ADS
No ADS

JavaFX ToggleButton Tutorial with Examples

  1. JavaFX ToggleButton
  2. ToggleButton example

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

ToggleButtonDemo.java
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 {

   @Override
   public void start(Stage stage) {

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

       // 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.setToggleGroup(group);
       femaleButton.setToggleGroup(group);

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

       maleButton.setSelected(true);

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

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

       stage.setTitle("ToggleButton (o7planning.org)");
       stage.setScene(scene);
       stage.show();
   }

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

}
No ADS

JavaFX Tutorials

Show More
No ADS