mouse-over popup menus
A GUI designer has asked us to make a JPopupMenu
where the menu items become visible when the mouse
goes over them, instead of when they are clicked.
It works pretty well with a MouseAdapter that overrides
mouseEntered() and sets the menu's getPopup() to visible.
There's a problem though. When the user wants to get
rid of the popup, in a normal JMenu they can click somewhere
outside the menu and the current popup disappears.
But with the popup that has become visible with mouse-over
it is always staying visible.
Does anybody know how this works in a standard JMenu?
I've been reading the sources but so far haven't found it.
Thanks. Source for running example below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Menus extends JFrame {
public Menus() {
super("Menus");
String [][] items = {
{ "Save" },
{ "File" , "Open", "Save As", },
{ "Edit", "Cut", "Copy", "Paste", "A long looooooooooooooong
item", },
{ "View", "Full screen", }
};
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
menuBar = new JMenuBar();
setJMenuBar(menuBar);
for (int i=0; i<items.length; i++) {
menu = new JMenu(items[i][0]);
menu.addMouseListener(new MouseL(menu));
menuBar.add(menu);
for (int j=1; j<items[i].length; j++) {
menuItem = new JMenuItem(items[i][j]);
menu.add(menuItem);
}
}
}
private static class MouseL extends MouseAdapter {
private final JMenu _menu;
private static JPopupMenu currentPopup = null;
MouseL(JMenu menu) {
_menu = menu;
}
public void mouseEntered(MouseEvent e) {
if (currentPopup != null) {
currentPopup.setVisible(false);
}
Point menuLoc = _menu.getLocation();
Dimension menuSiz = _menu.getPreferredSize();
// System.out.println("loc=" + menuLoc + ", siz=" +
menuSiz);
JPopupMenu popup = _menu.getPopupMenu();
popup.show(_menu, 0, menuSiz.height);
currentPopup = popup;
}
}
public static void main(String[] args) {
Menus frame = new Menus();
frame.setSize(new Dimension(400, 200));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}