Tim Tim - 6 months ago 50
Java Question

MouseEvent of JTabbedPane

I want to show a small popup menu when you right-click a tab, now this is working fine but when you right click it also selects that tab which is unwanted.

So my idea was to make a new class, extend JTabbedPane and recode those mouse events. Problem is that I have no idea where to start, I was browsing its source but I can't find what part is handeling the mouseEvents.

Tabs.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
if(me.getButton()==3){
int tabNr = ((TabbedPaneUI)Tabs.getUI()).tabForCoordinate(Tabs, me.getX(), me.getY());
Component clickedTab = EventsConfig.window.MainTabs.getComponentAt(tabNr);
newMenu(clickedTab, me.getX(), me.getY());
}
}
});

Answer

Beware: dirty hack ahead! The only reason I recommend it, is that I consider the behaviour (select on right press) a bug in the BasicTabbedPaneUI's Handler.

The basic idea is to grab the listener installed by the ui, remove it, wrap into a custom listener which delegates everything except a right pressed to the original and add that to the pane:

private void installMouseListenerWrapper(JComponent tabbedPane) {
    MouseListener handler = findUIMouseListener(tabbedPane);
    tabbedPane.removeMouseListener(handler);
    tabbedPane.addMouseListener(new MouseListenerWrapper(handler));
}

private MouseListener findUIMouseListener(JComponent tabbedPane) {
    MouseListener[] listeners = tabbedPane.getMouseListeners();
    for (MouseListener l : listeners) {
        if (l.getClass().getName().contains("$Handler")) {
            return l;
        }
    }
    return null;
}

public static class MouseListenerWrapper implements MouseListener {

    private MouseListener delegate;

    public MouseListenerWrapper(MouseListener delegate) {
        this.delegate = delegate;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        delegate.mouseClicked(e);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if (SwingUtilities.isRightMouseButton(e)) return;
        delegate.mousePressed(e);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        delegate.mouseReleased(e);
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        delegate.mouseEntered(e);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        delegate.mouseExited(e);
    }

}