2

I want to perform some action when a mouse is over JMenuItem. What listener should I use?

MarcoS
  • 13,386
  • 7
  • 42
  • 63
nicks
  • 2,161
  • 8
  • 49
  • 101

3 Answers3

5

Use MouseListener. Its method mouseEntered() and mouseExited() will be helpful to you.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • 1
    And what if i want to activate listener when navigating in menu with keyboard and not mouse? :S – nicks Apr 28 '11 at 14:01
2

If 'some action' happens to be 'show a message', look at JComponent.setToolTipText(String).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • .. yoooouuu suggesting a FocusListener? As we all know, it's usefulness is limited to very rare contexts :-) – kleopatra Apr 28 '11 at 13:16
  • 1
    @kleopatra: Yes, and apparently not menu items at all. A quick test suggests they do not fire on hover by mouse, or keyboard 'focus' as I would have thought of it. Butchering answer to suit. :P – Andrew Thompson Apr 28 '11 at 13:37
2

and alternative is

    menuItem1.getModel().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            ButtonModel model = (ButtonModel) e.getSource();
            if (model.isRollover()) {
                // some stuff
            }// may be another states from ButtonModel
        }
    });
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • sounds cool - just curious did you try it? Generally, it's a good-thing to go for a higher level state, if availabel. The only problem I see in practice, is that it's hard to get exactly a change in _rollover_ because changeEvent is a compound notification (or too fine-grained, depending on perspective) – kleopatra Apr 28 '11 at 13:17
  • And what if i want to activate listener when navigating in menu with keyboard and not mouse? – nicks Apr 28 '11 at 15:35
  • @Nika - yeah indeed, what did you find out when you tried it? – kleopatra Apr 28 '11 at 16:22
  • closing the circle: third iteration - http://stackoverflow.com/questions/5973875/why-my-changelistener-reacts-only-for-jmenu-and-not-for-jmenuitem – kleopatra May 12 '11 at 10:44