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;
008import javax.swing.event.ChangeEvent;
009import javax.swing.event.ChangeListener;
010
011/**
012 * An extension of JCheckBoxMenuItem that doesn't close the menu when selected.
013 *
014 * @author Darryl https://tips4java.wordpress.com/2010/09/12/keeping-menus-open/
015 */
016public class StayOpenCheckBoxMenuItem extends JCheckBoxMenuItem {
017
018  private static volatile MenuElement[] path;
019
020  {
021    getModel().addChangeListener(new ChangeListener() {
022
023      @Override
024      public void stateChanged(ChangeEvent e) {
025        if (getModel().isArmed() && isShowing()) {
026          path = MenuSelectionManager.defaultManager().getSelectedPath();
027        }
028      }
029    });
030  }
031
032  /**
033   * Contructs a new {@code StayOpenCheckBoxMenuItem} whose properties are taken from the Action supplied.
034   * @param a action
035   */
036  public StayOpenCheckBoxMenuItem(Action a) {
037    super(a);
038  }
039
040  /**
041   * Overridden to reopen the menu.
042   *
043   * @param pressTime the time to "hold down" the button, in milliseconds
044   */
045  @Override
046  public void doClick(int pressTime) {
047    super.doClick(pressTime);
048    MenuSelectionManager.defaultManager().setSelectedPath(path);
049  }
050}