這是一個快速和骯髒的例子添加一個上下文menue到一個圓圈。
public class ContextMenuDemo extends Application {
private StackPane root;
private Circle circle;
private ContextMenu contextMenu;
private MenuItem deleteItem;
public ContextMenuDemo() {
}
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
root = new StackPane();
circle = new Circle(200, 200, 100, Color.RED);
circle.setOnMousePressed(this::handleMousePressed);
root.getChildren().add(circle);
contextMenu = new ContextMenu();
deleteItem = new MenuItem("Delete");
deleteItem.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
root.getChildren().remove(circle);
}
});
contextMenu.getItems().add(deleteItem);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
protected void handleMousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
contextMenu.show((Node)e.getSource(), Side.RIGHT, 5, 5);
e.consume();
}
}
}