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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With