Java Reference
In-Depth Information
The following items are of particular note in Listing 6-2:
The top area of the
BorderPane will contain the MenuBar and ToolBar shown in Figure 6-1 ,
created by the createMenus() and createToolBar() methods that we walk through soon.
The center area of the
BorderPane will contain the TabPane shown in Figure 6-1 , created by the
createTabs() method that we walk through soon as well.
A style sheet named
starterApp.css is loaded, which we refer to later when discussing
relevant functionality.
Creating a Menu and Defining Menu Items
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
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;
}
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 16 ×16 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.
 
Search WWH ::




Custom Search