javaswingjmenubarmouse-listeners

Activate JMenuBar on hover


The JMenuBar does not start showing JMenuItems as selected or displaying the JMenu popups until it is first clicked upon. After you click somewhere in the JMenuBar, all these items respond to mouse hovers.

I would like to bypass the initial click required and have it activated automatically upon a mouse hover. Is there a way to do this?


Solution

  • The way is to add a MouseListener on the JMenu and listen on events mouseEntered. In the event handlers, you just need to click on it using doClick. For example,

    jMenuFile.addMouseListener(new MouseListener(){
        public void mouseEntered(MouseEvent e) {
           jMenuFile.doClick();
        }
      ...
    });
    

    Once programmatically clicked on the mouse is entered, it opens the popup menu automatically. To activate an entire JMenuBar, you have to add a listener on each JMenu. For this purpose, it is better to create a listener object separately.

    I have two menu items on the bar, so I did:

    MouseListener ml = new MouseListener(){
        public void mouseClicked(MouseEvent e) {}
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {
            ((JMenu)e.getSource()).doClick();
        }
      };
      jMenuFile.addMouseListener(ml);
      jMenuHelp.addMouseListener(ml);
    

    If you have so many menu items on the bar, you can just iterate it:

    for (Component c: jMenuBar1.getComponents()) {
        if (c instanceof JMenu){
            c.addMouseListener(ml);
        }
    }