Java Reference
In-Depth Information
In addition to the code in the preceding snippet, the following snippet from Listing 6-1 contains an instance
variable from our StarterAppModel class that contains the objects that will be displayed in the ChoiceBox :
public ObservableList choiceBoxItems = FXCollections.observableArrayList(
"Choice A",
"Choice B",
"Choice C",
"Choice D"
);
Now we move on to a control named MenuButton whose appearance is similar to the ChoiceBox , but whose
behavior is similar to a Menu .
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:
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);
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.
Creating a ContextMenu
In Step 30 of the previous exercise, you clicked the secondary mouse button in a blank area of the ScrollPane shown
in Figure 6-11 , and a ContextMenu popped up, from which you chose a MenuItem . The following snippet from
Listing 6-12 realizes this behavior:
MenuItem contextA = new MenuItem("MenuItem A");
contextA.setOnAction(e -> System.out.println(e.getEventType()
+ " occurred on Menu Item A"));
MenuItem contextB = new MenuItem("MenuItem B");
final ContextMenu contextMenu = new ContextMenu(contextA, contextB);
ScrollPane scrollPane = new ScrollPane(variousControls);
...
scrollPane.setOnMousePressed((MouseEvent me) -> {
if (me.getButton() == MouseButton.SECONDARY) {
contextMenu.show(stage, me.getScreenX(), me.getScreenY());
}
});
 
Search WWH ::




Custom Search