右键单击选项卡时,我想显示一个小的弹出菜单,现在可以正常工作,但是右键单击它还会选择不需要的选项卡。

所以我的想法是制作一个新类,扩展JTabbedPane并重新编码那些鼠标事件。问题是我不知道从哪里开始,我在浏览它的source,但是找不到哪个部分在处理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());
        }
    }
});

最佳答案

当心:肮脏的骇客前进!我推荐它的唯一原因是,我认为该行为(按右键选择)是BasicTabbedPaneUI的Handler中的错误。

基本思想是获取ui安装的侦听器,将其删除,包装到一个自定义侦听器中,该侦听器委派除右键单击原始控件外的所有内容,然后将其添加到窗格中:

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);
    }

}

关于java - JTabbedPane的MouseEvent,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8080438/

10-11 22:20