Menu Item ToggleGroup : Menu « JavaFX « Java






Menu Item ToggleGroup

 
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.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.RadioMenuItemBuilder;
import javafx.scene.control.SeparatorMenuItem;
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(final Stage primaryStage) {
    primaryStage.setTitle("title");
    Group root = new Group();
    Scene scene = new Scene(root, 400, 300, Color.WHITE);

    MenuBar menuBar = new MenuBar();
    menuBar.prefWidthProperty().bind(primaryStage.widthProperty());

    Menu menu = new Menu("File");


    ToggleGroup modalGroup = new ToggleGroup();
    RadioMenuItem nonModalItem = RadioMenuItemBuilder.create().toggleGroup(modalGroup).text("On").selected(true).build();
    nonModalItem.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent event) {
        System.out.println("Action");
      }
    });

    menu.getItems().add(nonModalItem);
    RadioMenuItem modalItem = RadioMenuItemBuilder.create().toggleGroup(modalGroup).text("Off").selected(true).build();
    modalItem.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent event) {
        System.out.println("Action");
      }
    });
    menu.getItems().add(modalItem);
    menu.getItems().add(new SeparatorMenuItem());
    
    menuBar.getMenus().add(menu);
    root.getChildren().add(menuBar);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

   
  








Related examples in the same category

1.Add MenuItem to Menu and then add menu to MenuBar
2.Using submenu
3.Set accelerator for Menu
4.Menu with EventHandler
5.Set setMnemonicParsing
6.Using Menu to control a page