001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.util;
003
004import javax.swing.Action;
005import javax.swing.Icon;
006import javax.swing.JCheckBoxMenuItem;
007import javax.swing.MenuElement;
008import javax.swing.MenuSelectionManager;
009import javax.swing.event.ChangeEvent;
010import javax.swing.event.ChangeListener;
011
012
013/**
014 * An extension of JCheckBoxMenuItem that doesn't close the menu when selected.
015 *
016 * @author Darryl https://tips4java.wordpress.com/2010/09/12/keeping-menus-open/
017 */
018public class StayOpenCheckBoxMenuItem extends JCheckBoxMenuItem {
019
020  private static MenuElement[] path;
021
022  {
023    getModel().addChangeListener(new ChangeListener() {
024
025      @Override
026      public void stateChanged(ChangeEvent e) {
027        if (getModel().isArmed() && isShowing()) {
028          path = MenuSelectionManager.defaultManager().getSelectedPath();
029        }
030      }
031    });
032  }
033
034  /**
035   * @see JCheckBoxMenuItem#JCheckBoxMenuItem()
036   */
037  public StayOpenCheckBoxMenuItem() {
038    super();
039  }
040
041  /**
042   * @see JCheckBoxMenuItem#JCheckBoxMenuItem(Action)
043   */
044  public StayOpenCheckBoxMenuItem(Action a) {
045    super(a);
046  }
047
048  /**
049   * @see JCheckBoxMenuItem#JCheckBoxMenuItem(Icon)
050   */
051  public StayOpenCheckBoxMenuItem(Icon icon) {
052    super(icon);
053  }
054
055  /**
056   * @see JCheckBoxMenuItem#JCheckBoxMenuItem(String)
057   */
058  public StayOpenCheckBoxMenuItem(String text) {
059    super(text);
060  }
061
062  /**
063   * @see JCheckBoxMenuItem#JCheckBoxMenuItem(String, boolean)
064   */
065  public StayOpenCheckBoxMenuItem(String text, boolean selected) {
066    super(text, selected);
067  }
068
069  /**
070   * @see JCheckBoxMenuItem#JCheckBoxMenuItem(String, Icon)
071   */
072  public StayOpenCheckBoxMenuItem(String text, Icon icon) {
073    super(text, icon);
074  }
075
076  /**
077   * @see JCheckBoxMenuItem#JCheckBoxMenuItem(String, Icon, boolean)
078   */
079  public StayOpenCheckBoxMenuItem(String text, Icon icon, boolean selected) {
080    super(text, icon, selected);
081  }
082
083  /**
084   * Overridden to reopen the menu.
085   *
086   * @param pressTime the time to "hold down" the button, in milliseconds
087   */
088  @Override
089  public void doClick(int pressTime) {
090    super.doClick(pressTime);
091    MenuSelectionManager.defaultManager().setSelectedPath(path);
092  }
093}