4

How do I prevent a JMenuItem from closing the menu when the JMenuItem is clicked?

The JMenuItem is enabled.

So this is the scenario, I have 3 JMenuItems:

JMenuItem: A, B, C;

C displays an integer X.

A and B are used to increment or decrement X by a value of 1. If A or B is clicked, the default nature is that the menu will close upon click. I want to be able to repeatedly click A or B and have the menu remain up, and perform the associated 'action' upon each click.

Thanks!

Mateus
  • 4,863
  • 4
  • 24
  • 32
Philip Nguyen
  • 871
  • 2
  • 10
  • 29

1 Answers1

3

First, using a menu to do this may be the wrong approach. JSpinner seems more appropriate. However, to do this with a JMenuItem you can subclass the MenuItemUI of the LookAndFeel you are using, and override the doClick(...) method so that clearSelectionPath() is not called, which closes the menu when the item is clicked.

Example, if you are using the Motif LookAndFeel you can do this:

menuItem.setUI(new MotifMenuItemUI() {
    @Override
    protected void doClick(MenuSelectionManager msm) {
        menuItem.doClick(0);
    }
});

I haven't ever tried this myself but I think it will work.

Garrett Hall
  • 29,524
  • 10
  • 61
  • 76
  • As an alternative to changing the UI delegate, consider [`Action`](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html), shown [here](http://stackoverflow.com/a/5129757/230513). – trashgod Feb 08 '12 at 18:28
  • 2
    Well this stopped the menu from displaying the hover animation on that item, but clicking it still closes the menu. Could you please check it? – Tomáš Zato Jan 05 '16 at 05:54
  • @TomášZato for `JCheckBoxMenuItem`s, I found that I could just substitute them with `JCheckBox`es and they would function just as well. For `JMenuItems` perhaps a `JButton` would work. ([Source](https://www.experts-exchange.com/questions/23952024/How-do-I-tell-a-JMenuItem-to-not-close-the-JMenu.html)) – Leftist Tachyon Mar 27 '19 at 02:44