JavaFX RadioButton add event handler

Introduction

To Handle RadioButton action event in JavaFX

radioButton.setOnAction(e->{ 
        response.setText("Transport selected is train."); 
}); 
    
    

Full source



 
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage; 
 
public class Main extends Application { 
 
  private Label response; 
 
  public static void main(String[] args) {    launch(args);   
  } /*from   w w w.  j  a v a  2 s  .c  om*/
 
  public void start(Stage myStage) { 
    myStage.setTitle("Demonstrate Radio Buttons"); 
 
    FlowPane rootNode = new FlowPane(10, 10); 
 
    rootNode.setAlignment(Pos.CENTER); 
 
    Scene myScene = new Scene(rootNode, 220, 120); 
 
    myStage.setScene(myScene); 
 
    response = new Label(""); 
 
    // Create the radio buttons. 
    RadioButton rbOne = new RadioButton("One"); 
    RadioButton rbTwo = new RadioButton("Two"); 
    RadioButton rbThree = new RadioButton("Three"); 
 
    // Create a toggle group. 
    ToggleGroup tg = new ToggleGroup(); 
 
    // Add each button to a toggle group. 
    rbOne.setToggleGroup(tg); 
    rbTwo.setToggleGroup(tg); 
    rbThree.setToggleGroup(tg); 
 
    // Handle action events for the radio buttons. 
    rbOne.setOnAction(e->{ 
        response.setText("Transport selected is train."); 
    }); 
 
    rbTwo.setOnAction(e->{ 
        response.setText("Transport selected is car."); 
    }); 
 
    rbThree.setOnAction(e->{ 
        response.setText("Transport selected is airplane."); 
    }); 
 
    // Fire the event for the first selection. 
    rbOne.fire(); 
 
    // Add the label and buttons to the scene graph. 
    rootNode.getChildren().addAll(rbOne, rbTwo, rbThree, response); 
 
    myStage.show(); 
  } 
}



PreviousNext

Related