How to "close" a JMenu in an Event Handler - Java

132 views Asked by At

I have a simple MouseAdapter that I add to a JMenu. I want the menu to show its contents when moused over, react when clicked on, and hide its contents when the mouse leaves it. Here's where I add the listener:

      public final void addGuiReaction(Runnable clickReaction) {
            JMenu THIS = this;
            this.addMouseListener(new MouseAdapter() {
                final Runnable reaction = clickReaction;
                final JMenu source = THIS;
                @Override
                public void mouseClicked(MouseEvent arg0) {reaction.run();}
                @Override
                public void mouseEntered(MouseEvent arg0) {source.doClick();} // Opens the menu
                @Override
                public void mouseExited(MouseEvent arg0) {/* Need to "close" the menu */}
            });
      }

This works just fine for both the reaction and the open when moused over functionality, but I can't figure out how to close it. Tried both setSelected(false) and setPopupMenuVisible(false) but the issue with both is that the menu doesn't open again the next time I mouse over it.

Anyone knows a nice way of closing the menu?

1

There are 1 answers

0
Ivo Andonov On

Answering to "How to close the JMenu..."

In place of this:

/* Need to "close" the menu */

You can put this:

source.dispatchEvent(new KeyEvent(source, KeyEvent.KEY_PRESSED, 0, 0, KeyEvent.VK_ESCAPE));

Hence simulate the ESC key press which will trigger the respective Action from the ActionMap of the JMenuBar.

However this will not fully solve your problem as while the keyboard arrow keys will work, you will not be able to use the mouse to select any of the items of the JMenu as trying to enter any of them will trigger the JMenu mouseExited event. You may need to attach a proper mouse event listener to the menu items as well.