Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

contextmenu - How to disable the default context menu on a text field

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...