I am trying to have a JavaFX Pane
(VBox
in my case, but I don't think it matters) that has a ContextMenu
that behaves correctly.
I have found these two questions: why Pane
s can't have ContextMenu
s and How to create ContextMenu
within a Pane
.
The problem I'm having with these two solutions (which are very similar) is that while the context menu correctly disappears if I click on the pane, it doesn't disappear if I click inside a control within that pane. The simplest way to observe this flaw is to create such a pane with a TextField
. Right-click on the pane to show the context menu, then click inside to TextField
to focus on it. While a proper context menu would disappear at this point, this "hacked-in" context menu (for lack of a better term) happily stays in it's place, possibly blocking the user's view of the text field they are trying to fill.
Now, I know I can add a change listener to the focused
property of each and every control on my pane, but that feels redundant. Is there a better way to make sure the context menu is hidden when a control in my pane is selected (or, more accurately - when the user click the mouse anywhere in the owning window outside the context menu)?
What I tried so far and doesn't work -
- Adding a change listener to the pane's
focused
property - it appears the pane isn't considered focused if one of it's children is - Adding a change listener to the context menu's
focused
property - it appears the context menu's focus isn't changed when clicking outside of it.