001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.util;
003
004import javax.swing.Action;
005import javax.swing.JCheckBoxMenuItem;
006import javax.swing.MenuElement;
007import javax.swing.MenuSelectionManager;
008
009/**
010 * An extension of JCheckBoxMenuItem that doesn't close the menu when selected.
011 *
012 * @author Darryl Burke https://tips4java.wordpress.com/2010/09/12/keeping-menus-open/
013 */
014public class StayOpenCheckBoxMenuItem extends JCheckBoxMenuItem {
015
016    private MenuElement[] path;
017
018    {
019        getModel().addChangeListener(e -> {
020            if (getModel().isArmed() && isShowing()) {
021                path = MenuSelectionManager.defaultManager().getSelectedPath();
022            }
023        });
024    }
025
026    /**
027     * Constructs a new initially unselected {@code StayOpenCheckBoxMenuItem} with no set text or icon.
028     * @see JCheckBoxMenuItem#JCheckBoxMenuItem()
029     */
030    public StayOpenCheckBoxMenuItem() {
031        super();
032    }
033
034    /**
035     * Constructs a new {@code StayOpenCheckBoxMenuItem} whose properties are taken from the Action supplied.
036     * @param a action
037     * @see JCheckBoxMenuItem#JCheckBoxMenuItem(Action)
038     */
039    public StayOpenCheckBoxMenuItem(Action a) {
040        super(a);
041    }
042
043    /**
044     * Overridden to reopen the menu.
045     *
046     * @param pressTime the time to "hold down" the button, in milliseconds
047     */
048    @Override
049    public void doClick(int pressTime) {
050        super.doClick(pressTime);
051        MenuSelectionManager.defaultManager().setSelectedPath(path);
052    }
053}