Gurce
Gurce

Reputation: 664

Is there a way to cancel the popup menu within popupMenuWillBecomeVisible()?

In my java app, I've been using the popupMenuWillBecomeVisible() event to decide on which menu-items within my JPopupMenu will be enabled/disabled/visible/hidden, etc.

I've used the JPopupMenu as a right-click context menu of a JList, and I decide on the state of the menu-items depending on which item in the list was right-clicked.

This is all working fine. The only gotchya I have is for the case where the list is empty, or the right-click was triggered when no item was selected.

For this case, I was hoping that I could cancel the appearance of the JPopupMenu from within the popupMenuWillBecomeVisible() event, as that's where I currently perform my existing tests.

Is there a way to do this? Perhaps some sort of way to 'consume' the event?

If not, perhaps my only other option will be to try alternatives, such as moving the testing logic somewhere else, prior to the right-click.

Still, my preference at this stage was to keep the logic within popupMenuWillBecomeVisible(), unless that proves to be impossible.

Anyone got any ideas?

Upvotes: 2

Views: 1529

Answers (1)

MircoProgram
MircoProgram

Reputation: 289

SwingUtilities.InvokeLater will wait until all AWT operations are finished before starting the runnable, which means this runnable will be called after the popupMenuWillBecomeVisible event is finished and the popup menu is visible or in queue to be painted.

        final JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.addPopupMenuListener(new PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        ((JPopupMenu)e.getSource()).setVisible(false);
                    }
                });
            }

Upvotes: 3

Related Questions