MenuBar createMenus() {
MenuItem itemNew = new MenuItem("New...", new ImageView(
new Image(getClass().getResourceAsStream("images/paper.png"))));
itemNew.setAccelerator(KeyCombination.keyCombination("Ctrl+N"));
itemNew.setOnAction(e -> System.out.println(e.getEventType()
+ " occurred on MenuItem New"));
MenuItem itemSave = new MenuItem("Save");
Menu menuFile = new Menu("File");
menuFile.getItems().addAll(itemNew, itemSave);
MenuItem itemCut = new MenuItem("Cut");
MenuItem itemCopy = new MenuItem("Copy");
MenuItem itemPaste = new MenuItem("Paste");
Menu menuEdit = new Menu("Edit");
menuEdit.getItems().addAll(itemCut, itemCopy, itemPaste);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().addAll(menuFile, menuEdit);
return menuBar;
}
메뉴 만들기
To create the menu structure, our StarterApp program defines a method that we’ve arbitrarily named createMenus(), shown in Listing 6-3. This method returns a MenuBar instance that contains the desired menu structure.
Listing 6-3. The createMenus() Method Located in StarterAppMain.java
As previously shown in Figure 6-2, in addition to a title, menu items often have a graphic and an accelerator key combination. In the following snippet from Listing 5-3, the menu item named New is defined with a title, graphic, and an accelerator key, as well as an action to be performed when the menu item is selected.
MenuItem itemNew = new MenuItem("New...", new ImageView(
new Image(getClass().getResourceAsStream("images/paper.png"))));
itemNew.setAccelerator(KeyCombination.keyCombination("Ctrl+N"));
itemNew.setOnAction(e -> System.out.println(e.getEventType()
+ " occurred on MenuItem New"));
The recommended size for a menu item graphic is 16x16 pixels, which is the size of the graphic used in the New menu item of the StarterApp program. To load the graphic from the file system, the argument supplied to the Image constructor in the preceding snippet causes the same class loader that loaded the StarterAppMain class to load the paper.png file. This paper.png file is loaded from the images directory subordinate to the location of the StartAppMain.class file.
To define the Ctrl+N accelerator key combination, the static keyCombination() method of the KeyCombination class is used to create a KeyCombination instance. This instance is passed into the setAccelerator() method of the MenuItem.
The onAction() event handler in the preceding snippet defines a lambda expression that is invoked when the user selects the New menu item. The resulting message printed to the Java console is the one to which Step 2 of the earlier exercise refers.