Wednesday 30 May 2018

JavaFX: Add toggle buttons to a group

By using 'setToggleGroup' method of ToggleButton class, you can add toggle buttons to a group. At any point of time, you can able to select only one toggle button from a specific group.

Ex
ToggleGroup toggleGroup = new ToggleGroup();

ToggleButton toggleButton1 = new ToggleButton("Toggle Button 1");
ToggleButton toggleButton2 = new ToggleButton("Toggle Button 2");
ToggleButton toggleButton3 = new ToggleButton("toggle button 3");

toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);

ToggleButtonApp.java
package com.sample.demos;

import java.io.FileNotFoundException;
import java.net.MalformedURLException;

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

public class ToggleButtonApp extends Application {

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {
  ToggleGroup toggleGroup = new ToggleGroup();

  ToggleButton toggleButton1 = new ToggleButton("Toggle Button 1");
  ToggleButton toggleButton2 = new ToggleButton("Toggle Button 2");
  ToggleButton toggleButton3 = new ToggleButton("toggle button 3");

  toggleButton1.setToggleGroup(toggleGroup);
  toggleButton2.setToggleGroup(toggleGroup);
  toggleButton3.setToggleGroup(toggleGroup);
  
  HBox hbox = new HBox(toggleButton1, toggleButton2, toggleButton3);

  hbox.setAlignment(Pos.TOP_CENTER);

  Scene scene = new Scene(hbox, 800, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Toggle Button Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(ToggleButtonApp.class, args);
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment