How to create a Toggle Button in JavaFX?

JavaFXObject Oriented ProgrammingProgramming

A button is a component, which performs an action (like submit, login, etc..) when pressed. It is usually labeled with a text or an image specifying the respective action.

A toggle button indicates whether it is elected or not, using toggle button(s) you can switch between multiple states. Generally, multiple toggle buttons are grouped and you can select only one at a time.

You can create a toggle button in JavaFX by instantiating the javafx.scene.control.ToggleButton class. You can assign a toggle button to a group using the setToggleGroup() method.

Only one button will be selected in a toggle group, unlike the radio button if you click on the selected toggle button it will be un-selected.

Example

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ToggledButtonExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating toggle buttons
      ToggleButton button1 = new ToggleButton("Java");
      ToggleButton button2 = new ToggleButton("Python");
      ToggleButton button3 = new ToggleButton("C++");
      //Toggle button group
      ToggleGroup group = new ToggleGroup();
      button1.setToggleGroup(group);
      button2.setToggleGroup(group);
      button3.setToggleGroup(group);
      //Adding the toggle button to the pane
      VBox box = new VBox(5);
      box.setFillWidth(false);
      box.setPadding(new Insets(5, 5, 5, 50));
      box.getChildren().addAll(button1, button2, button3);
      //Setting the stage
      Scene scene = new Scene(box, 595, 150, Color.BEIGE);
      stage.setTitle("Toggled Button Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 16-May-2020 10:59:10
Advertisements