我找到了一种禁用默认弹出菜单的方法。然后您可以添加自己的,而不会获得双菜单效果。
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);
}
});
注意 - 我不是通过组合框上的菜单添加我自己的菜单,我不确定这是否可行(它可能)。
如果您将组合框包装在 Hbox 中,并向 hbox 添加菜单 - 我知道这会起作用。
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());
}
});