如何全局禁用默认上下文菜单
How to disable the default context menu globally
以下代码禁用添加到 Scene
的所有现有 TextField
的默认上下文菜单。
for (Node node : scene.getRoot().lookupAll("*")) {
if (node instanceof TextField) {
((TextField)node).setContextMenu(new ContextMenu());
}
}
但如果您稍后将另一个 TextField
添加到 Scene
,其默认上下文菜单不会被禁用。
如果你运行上面的代码每次都加上TextField
s,是没有问题的,就是比较麻烦。
那么有没有办法禁用所有TextField
(包括后来添加到场景图中的)的默认上下文菜单?
您可以使用 CSS 删除 TextField
个对象的上下文菜单:
.text-field * .context-menu {
visibility: hidden;
}
.text-field * .context-menu > .scroll-arrow {
-fx-opacity: 0;
}
第一个样式 class 隐藏了 ContextMenu
本身。第二个隐藏小箭头
CONTEXT_MENU_REQUESTED
event 可以在到达目标 Node
之前被添加到 Scene
或添加到包含所有 Parent
的事件过滤器消耗掉=16=]不应打开上下文菜单的:
scene.addEventFilter(ContextMenuEvent.CONTEXT_MENU_REQUESTED, evt -> {
if (checkTextField((Node) evt.getTarget())) {
evt.consume();
}
});
// check, if the node is part of a TextField
public static boolean checkTextField(Node node) {
while (node != null) {
if (node instanceof TextField) {
return true;
}
node = node.getParent();
}
return false;
}
以下代码禁用添加到 Scene
的所有现有 TextField
的默认上下文菜单。
for (Node node : scene.getRoot().lookupAll("*")) {
if (node instanceof TextField) {
((TextField)node).setContextMenu(new ContextMenu());
}
}
但如果您稍后将另一个 TextField
添加到 Scene
,其默认上下文菜单不会被禁用。
如果你运行上面的代码每次都加上TextField
s,是没有问题的,就是比较麻烦。
那么有没有办法禁用所有TextField
(包括后来添加到场景图中的)的默认上下文菜单?
您可以使用 CSS 删除 TextField
个对象的上下文菜单:
.text-field * .context-menu {
visibility: hidden;
}
.text-field * .context-menu > .scroll-arrow {
-fx-opacity: 0;
}
第一个样式 class 隐藏了 ContextMenu
本身。第二个隐藏小箭头
CONTEXT_MENU_REQUESTED
event 可以在到达目标 Node
之前被添加到 Scene
或添加到包含所有 Parent
的事件过滤器消耗掉=16=]不应打开上下文菜单的:
scene.addEventFilter(ContextMenuEvent.CONTEXT_MENU_REQUESTED, evt -> {
if (checkTextField((Node) evt.getTarget())) {
evt.consume();
}
});
// check, if the node is part of a TextField
public static boolean checkTextField(Node node) {
while (node != null) {
if (node instanceof TextField) {
return true;
}
node = node.getParent();
}
return false;
}