2

I want to highlight some elements on screen, when one JMenuItem in PopupMenu ist selected(mouse over). So i use MouseListener on my JMenuItem with

        @Override
        public void mouseEntered(MouseEvent e) {
            highlightOn();
        }

        @Override
        public void mouseExited(MouseEvent e) {
            highlightOff();
        }

It works fine, but if i press Esc the popup menu will be closed, without clean the highligt. How can i intercept the closing of JPopupMenu to handle this?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
AvrDragon
  • 7,139
  • 4
  • 27
  • 42

2 Answers2

7

Something like this should do the trick:

myPopupMenu.addPopupMenuListener(new PopupMenuListener() {

     @Override
     public void popupMenuCanceled(final PopupMenuEvent e) {
         highlightOff();
     }

     @Override
     public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {
         highlightOff();
     }

     @Override
     public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { }
}

Just remember to add the listener before you make it visible, or inside its constructor.

tucuxi
  • 17,561
  • 2
  • 43
  • 74
  • +1 for PopupMenuListener, btw JMenuXxx have got own another Listeners, PopupMenuListener this doesn't works for particular JMenuItem is highlighted.... or deselected – mKorbel Jul 19 '12 at 16:06
4

you look at

  1. PopupMenuListener

better could be

  1. JMenuItem(s) can returns ButtonModel,

  2. ButtonModel returns isRollover(), isArmend(), isPressed() e.i.

  3. each of JButtons JComponents (JButton, JCheckBox, JRadioButton and JMenuXxx) implemented diferrent methods from ButtonModel

mKorbel
  • 109,525
  • 20
  • 134
  • 319