Set accelerator for Menu : Menu « JavaFX « Java






Set accelerator for Menu

 
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.control.SeparatorMenuItem;
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("Keyboard");
        Group root = new Group();
        Scene scene = new Scene(root, 530, 300, Color.WHITE);

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

        Menu menu = new Menu("File");
        menuBar.getMenus().add(menu);

        MenuItem newItem = MenuItemBuilder.create()
                .text("New")
                .accelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN))
                .onAction(new EventHandler<ActionEvent>() {
                        public void handle(ActionEvent event) {
                            System.out.println("Ctrl-N");
                        }
                    })
                .build();
        menu.getItems().add(newItem);


        MenuItem saveItem = MenuItemBuilder.create()
                .text("Save")
                .accelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN))
                .onAction(new EventHandler<ActionEvent>() {
                        public void handle(ActionEvent event) {
                          System.out.println("Ctrl-S");
                        }
                    })
                .build();
        menu.getItems().add(saveItem);

        menu.getItems().add(new SeparatorMenuItem());

        MenuItem exitItem = MenuItemBuilder.create()
                .text("Exit")
                .accelerator(new KeyCodeCombination(KeyCode.X, KeyCombination.CONTROL_DOWN))
                .onAction(new EventHandler<ActionEvent>() {
                        public void handle(ActionEvent event) {
                          System.out.println("Ctrl-X");
                        }
                    })
                .build();
        menu.getItems().add(exitItem);

        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.Menu with EventHandler
4.Menu Item ToggleGroup
5.Set setMnemonicParsing
6.Using Menu to control a page