Reputation: 59
The following code disables the default context menu of all the existing TextField
added to Scene
.
for (Node node : scene.getRoot().lookupAll("*")) {
if (node instanceof TextField) {
((TextField)node).setContextMenu(new ContextMenu());
}
}
But if you add another TextField
to Scene
later, its default context menu is not disabled.
If you run the code above each time you add TextField
s, there would be no problem, but it is rather troublesome.
So are there any way to disable the default context menu of all the TextField
(including ones added in the scene graph later)?
Upvotes: 1
Views: 961
Reputation: 21799
You can use CSS to remove the context menu of TextField
objects:
.text-field * .context-menu {
visibility: hidden;
}
.text-field * .context-menu > .scroll-arrow {
-fx-opacity: 0;
}
The first style class hides ContextMenu
itself. The second one hides the small arrow.
Upvotes: 1
Reputation: 82451
The CONTEXT_MENU_REQUESTED
event can be consumed before it reaches the target Node
by a event filter that is added to the Scene
or to a Parent
containing all the TextField
s that should not open the context menu:
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;
}
Upvotes: 2