JavaFX ToggleButton handle event

Introduction

To Handle ToggleButton action event in JavaFX

// Handle action events for the toggle button.
    tbOnOff.setOnAction(e -> {//w  w  w.  j  a  v  a2  s. c  o m
      if (tbOnOff.isSelected())
        response.setText("Button is on.");
      else
        response.setText("Button is off.");

    });
    
    

Full source

// Demonstrate a toggle button. 

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class Main extends Application {

  ToggleButton tbOnOff;/*from  w  w  w .j a  v a2  s  .  c om*/
  Label response;

  public static void main(String[] args) {

    launch(args);
  }

  public void start(Stage myStage) {
    myStage.setTitle("Demonstrate a Toggle Button");

    FlowPane rootNode = new FlowPane(10, 10);

    rootNode.setAlignment(Pos.CENTER);

    Scene myScene = new Scene(rootNode, 220, 120);

    myStage.setScene(myScene);

    // Create a label.
    response = new Label("Push the Button.");

    // Create the toggle button.
    tbOnOff = new ToggleButton("On/Off");

    // Handle action events for the toggle button.
    tbOnOff.setOnAction(e -> {
      if (tbOnOff.isSelected())
        response.setText("Button is on.");
      else
        response.setText("Button is off.");

    });

    // Add the label and buttons to the scene graph.
    rootNode.getChildren().addAll(tbOnOff, response);

    myStage.show();
  }
}



PreviousNext

Related