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