Forcing a JPopupMenu to disable hover effects on its owner JFrame?

1.7k views Asked by At

When i right click on a JTable in a JFrame I show a JPopupMenu. If I left this JPopupMenu shown as it is and moved with the mouse to the JTable I can still hover on its rows.

This is not the default behavior of Windows applications. In normal case if a popup menu appears in a program it blocks any hover actions on the popup owner window.

Can i do the same thing in Java ?

2

There are 2 answers

1
klonq On

One way to approach this problem is to set an instance variable in one of your GUI elements to flag whether or not to enable hover events. I have shown below how this may work, but it's not in its complete form, you will also need to re-enable hover when the JPopupMenu is dismissed, and also check the state of the ENABLE_HOVER field before firing hover effects.

public MyTable extends JTable {

    private boolean ENABLE_HOVER = true;

    public MyTable() {
    ...
    this.addMouseListener(new MouseListener(){
        ...
        public void mouseClicked(MouseEvent e) {
            if (isRightClick(e)) {
                setHoverEnabled(false);
                showJPopupMenu();
            }
        }
    });
    }

    protected void setHoverEnabled(final boolean hover) {
        this.ENABLE_HOVER = hover;
    }
}
0
klonq On

Another method which may be better suited to disabling multitudes of however enabled elements is to intercept the events at the glass pane. An example of how this might work is shown here. Be warned though if your interface is already built it may require significant re-jigging of your component classes.

You will need to intercept all events at the glass pane, if hover is enabled (no popup menu shown) you would pass the event to the appropriate component. Otherwise if hover is disabled and the MouseEvent occurred over the JPopupMenu is passed only to the JPopupMenu.