Class ContextMenu

java.lang.Object
All Implemented Interfaces:
Styleable, EventTarget, Skinnable

@IDProperty("id") public class ContextMenu extends PopupControl

A popup control containing an ObservableList of menu items. The items ObservableList allows for any MenuItem type to be inserted, including its subclasses Menu, MenuItem, RadioMenuItem, CheckMenuItem and CustomMenuItem. If an arbitrary Node needs to be inserted into a menu, a CustomMenuItem can be used. One exception to this general rule is that SeparatorMenuItem could be used for inserting a separator.

A common use case for this class is creating and showing context menus to users. To create a context menu using ContextMenu you can do the following:

final ContextMenu contextMenu = new ContextMenu();
contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent e) {
        System.out.println("showing");
    }
});
contextMenu.setOnShown(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent e) {
        System.out.println("shown");
    }
});

MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent e) {
        System.out.println("About");
    }
});
MenuItem item2 = new MenuItem("Preferences");
item2.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent e) {
        System.out.println("Preferences");
    }
});
contextMenu.getItems().addAll(item1, item2);

final TextField textField = new TextField("Type Something");
textField.setContextMenu(contextMenu);
Image of the ContextMenu control

Control.setContextMenu(javafx.scene.control.ContextMenu) convenience method can be used to set a context menu on on any control. The example above results in the context menu being displayed on the right Side of the TextField. Alternatively, an event handler can also be set on the control to invoke the context menu as shown below.

textField.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent e) {
        contextMenu.show(textField, Side.BOTTOM, 0, 0);
    }
});

Group root = (Group) scene.getRoot();
root.getChildren().add(textField);

In this example, the context menu is shown when the user clicks on the Button (of course, you should use the MenuButton control to do this rather than doing the above).

Note that the show function used in the code sample above will result in the ContextMenu appearing directly beneath the TextField. You can vary the Side to get the results you expect.

Since:
JavaFX 2.0
See Also: