views:

185

answers:

2

When i run the code above the frame's menu bar come up when the mouse moves to the upper part of the window. The problem is when i open the menu but do not select any item and move out the mouse the menu bar get invisible but the items stay on screen.

What i'm going to archive is a "auto-hide" menu bar that get be visible when the mouse enters a certain region in the JFrame.

public class Test extends JFrame {

    public Test() {
        setLayout(new BorderLayout());
        setSize(300, 300);

        JMenuBar mb = new JMenuBar();
        setJMenuBar(mb);
        mb.setVisible(false);


        JMenu menu = new JMenu("File");
        mb.add(menu);

        menu.add(new JMenuItem("Item-1"));
        menu.add(new JMenuItem("Item-2"));

        addMouseMotionListener(new MouseAdapter() {

            @Override
            public void mouseMoved(MouseEvent e) {
                getJMenuBar().setVisible(e.getY() < 50);
            }
        });
    }

    public static void main(String args[]) {
        new Test().setVisible(true);
    }
}

Update

I think i found a workaround: if the menu bar is visible and the JFrame receives a mouse move event then send the ESC key to close any open menu.

 addMouseMotionListener(new MouseAdapter() {

            @Override
            public void mouseMoved(MouseEvent e) {
                if (getJMenuBar().isVisible()) {
                    try {
                        Robot robot = new Robot();
                        robot.keyPress(KeyEvent.VK_ESCAPE);
                    } catch (AWTException ex) {
                    }

                }
                getJMenuBar().setVisible(e.getY() < 50);
            }
        });

This workaround depends on the look and feel (meaning of the ESC key). Anyway, for me it is ok.

A: 

You could check to see if the menu is showing, and not hide the menu bar if it is:

        public void mouseMoved(MouseEvent e) {
            JMenuBar temp = getJMenuBar();
            if(!temp.isShowing()) {
                temp.setVisible(e.getY() < 50);
            }
        }
Rulmeq
Once it is shown, it won't hide anymore, with this method.
Gnoupi
Yeah, forget that. It's the menu bar I'm checking not the pop-up
Rulmeq
+2  A: 

You can probably make it work by checking is any menu is selected, from the JMenuBar:

public void mouseMoved(MouseEvent e) {
    JMenuBar lMenu = getJMenuBar();
    boolean hasSelectedMenu = false;
    for (int i=0 ; i< lMenu.getMenuCount() ; ++i)
    {
        if (lMenu.getMenu(i).isSelected())
        {
            hasSelectedMenu = true;
            break;
        }
    }

    if(!hasSelectedMenu)
        lMenu.setVisible(e.getY() < 50);
}

In this case, it would disappear as soon as you click somewhere else in the JFrame.

However, not exactly, as it would update only on mouseMoved. I would recommend you to do the same check on mouseClicked, to be sure it disappears when clicking without moving.

Gnoupi