RadioMenuItem on Action listener : RadioMenuItem « JavaFX « Java






RadioMenuItem on Action listener

 

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.RadioMenuItemBuilder;
import javafx.scene.control.ToggleGroup;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Menus");
        Group root = new Group();
        Scene scene = new Scene(root, 300, 250, Color.WHITE);
        
        MenuBar menuBar = new MenuBar();
        
        Menu menu = new Menu("Radio Button Menu Item");
        ToggleGroup tGroup = new ToggleGroup();
        RadioMenuItem soundAlarmItem = RadioMenuItemBuilder.create()
                .toggleGroup(tGroup)
                .text("On")
                .build();
        RadioMenuItem stopAlarmItem = RadioMenuItemBuilder.create()
                .toggleGroup(tGroup)
                .text("Off")
                .selected(true)
                .build();
        
        stopAlarmItem.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent e) {
              System.out.println("radio toggled");
          }
        });
        
        menu.getItems().add(soundAlarmItem);
        menu.getItems().add(stopAlarmItem);
        
        menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
        menuBar.getMenus().add(menu);
        
        root.getChildren().add(menuBar); 
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

   
  








Related examples in the same category

1.Add RadioMenuItem to Menu