Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab component consuming mouse so tabs won't change

I have a problem that when I add a mouse listener to a component that is used as a tab, I can't switch tabs.

This demonstrates the problem:

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

public class JTabBug {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JTabbedPane jTabbedPane = new JTabbedPane();
                jTabbedPane.addTab("Red", new JLabel("Roses"));
                jTabbedPane.addTab("Blue", new JLabel("Skies"));
                jTabbedPane.addTab("Green", new JLabel("Grass"));

                for (int i = 0; i < jTabbedPane.getTabCount(); i++) {
                    JLabel tabComponent = new JLabel(jTabbedPane.getTitleAt(i));

                    tabComponent.addMouseMotionListener(new MouseMotionAdapter() {
                        @Override
                        public void mouseDragged(MouseEvent e) {
                            System.out.println("dragging");
                        }
                    });
                    jTabbedPane.setTabComponentAt(i, tabComponent);
                }

                JFrame jFrame = new JFrame("Testing");
                jFrame.add(jTabbedPane);
                jFrame.setSize(400, 500);
                jFrame.setVisible(true);
                jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}

dragging is printed out as expected but you can't change tabs.

like image 827
Boomah Avatar asked Nov 15 '22 05:11

Boomah


1 Answers

Override the contains method of your tab component (a JLabel in your case) to return false.

        public boolean contains(int x, int y)
        {
            return false;
        }
like image 120
Avrom Avatar answered Dec 18 '22 22:12

Avrom