Build a MenuItem, set action, accelerator with MenuItemBuilder : MenuItemBuilder « JavaFX « Java






Build a MenuItem, set action, accelerator with MenuItemBuilder

 

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.MenuItemBuilder;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
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("File");
        final MenuItem aboutMenuItem =
            MenuItemBuilder.create()
                           .text("About")
                           .onAction(
                               new EventHandler<ActionEvent>()
                               {
                                  @Override public void handle(ActionEvent e)
                                  {
                                     System.out.println("You clicked on About!");
                                  }
                               })
                           .accelerator(
                               new KeyCodeCombination(
                                  KeyCode.A, KeyCombination.CONTROL_DOWN))
                           .build();             
         menu.getItems().add(aboutMenuItem);


        
        menuBar.getMenus().add(menu);
        
        menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
        
        root.getChildren().add(menuBar); 
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

   
  








Related examples in the same category