MenuItem menuA = new MenuItem("MenuItem A");
menuA.setOnAction(e -> System.out.println(e.getEventType() + " occurred on Menu Item A"));
MenuItem menuB = new MenuItem("MenuItem B");
MenuButton menuButton = new MenuButton("MenuButton");
menuButton.getItems().addAll(menuA, menuB);
Using a MenuButton
When clicked, a MenuButton control pops up a context menu that contains MenuItem instances from which to choose. In Step 21 of the previous exercise, you clicked the MenuButton control shown in Figure 6-9. As a result, a message was printed to the Java console indicating which MenuItem you chose. The following code snippet, from Listing 6-12, implements this functionality in the StarterApp program:
Because of the similarity between the MenuButton and Menu classes, the concepts in the previous snippet are covered in the section “Creating a Menu and Defining Menu Items” earlier in the chapter. One of the distinguishing features of MenuButton is the popupSide property, which enables you to choose on which side of the MenuButton the ContextMenu should pop up.
Another way to pop up a ContextMenu that doesn’t require using a MenuButton is our next topic of discussion.