1

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 TextFields, 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)?

1
  • 2
    You can always make your own TextField implementation which does this upon creation, or use a factory method that does this for you. What is the usecase?
    – Itai
    Commented Jul 17, 2016 at 3:03

2 Answers 2

2

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 TextFields 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;
}
1

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.