本文介绍了如何在javaFX中右键单击窗格或ImageView时显示上下文菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试显示我创建的上下文菜单,当我右键单击窗格或图像视图时((在请求的上下文菜单上))。问题是它们似乎没有 setContextMenue 方法,与标签和按钮等不同。如何将上下文菜单关联到似乎不接受上下文菜单的节点?
I am trying to show a context menu i created, when i right click on a pane or an image view ((on Context Menu Requested)). The problem is they don't seem to have a setContextMenue method, unlike labels and buttons...etc. How can associate a context menu to a node that doesn't seem to accept context menus?
@FXML
Button button1, button2;
@FXML
Pane mainPane;
@FXML
ImageView image;
private void initContextMenu() {
final ContextMenu contextMenu = new ContextMenu();
final MenuItem item1 = new MenuItem("open a file");
final MenuItem item2 = new MenuItem("quit");
contextMenu.getItems().addAll(item1, item2);
// not possible
image.setContextMenu(contextMenu);
// possible
button1.setContextMenu(contextMenu)
推荐答案
你可以做到
image.setOnContextMenuRequested(e ->
contextMenu.show(image, e.getScreenX(), e.getScreenY()));
这篇关于如何在javaFX中右键单击窗格或ImageView时显示上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!