By default the JavaFX TextField
has a built in ContextMenu
with 'undo', 'copy', 'cut' etc. options. The ComboBox
also has the same ContextMenu
when it is set as editable (the ComboBox
is actually part of the editor which is a TextField
).
I want to replace this ContextMenu
with a custom one but I'm having a problem with disabling the default one.
I have tried consuming the ContextMenu
and mouse click events but ComboBox
and ComboBox.getEditor()
both have a null ContextMenu
.
Am I missing something?
I have found a way to disable the default popup menu. Then you can add your own, without getting the double menu effect.
ComboBox<String> cb_ = new ComboBox<>();
final EventDispatcher initial = cb_.getEditor().getEventDispatcher();
cb_.getEditor().setEventDispatcher(new EventDispatcher()
{
@Override
public Event dispatchEvent(Event event, EventDispatchChain tail)
{
if (event instanceof MouseEvent)
{
//shot in the dark guess for OSX, might not work
MouseEvent mouseEvent = (MouseEvent)event;
if (mouseEvent.getButton() == MouseButton.SECONDARY ||
(mouseEvent.getButton() == MouseButton.PRIMARY && mouseEvent.isControlDown()))
{
event.consume();
}
}
return initial.dispatchEvent(event, tail);
}
});
Note - I'm not adding my own menu via the menus on the combobox, I'm not sure if that will work (it might).
If you wrap the combobox in an Hbox, and add a menu to the hbox - I know that will work.
HBox hbox = new HBox();
ContextMenu contextMenu = new ContextMenu();
....
hbox.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
@Override
public void handle(ContextMenuEvent event)
{
contextMenu.show(hbox, event.getScreenX(), event.getScreenY());
}
});