1616import java .awt .Point ;
1717import java .awt .event .MouseAdapter ;
1818import java .awt .event .MouseEvent ;
19+ import java .awt .event .MouseListener ;
1920
2021public class ClosableTabTitlePane {
2122 private final JPanel ui ;
@@ -29,8 +30,34 @@ public ClosableTabTitlePane(String title, String tooltip, Runnable onClose) {
2930 this .ui = new JPanel (new FlowLayout (FlowLayout .CENTER , 2 , 2 ));
3031 this .ui .setOpaque (false );
3132
33+ final MouseListener mousePressedDispatcher = GuiUtil .onMousePress (e -> {
34+ // for some reason registering a mouse listener on this or any child makes
35+ // events never go to the tabbed pane, so we have to redirect
36+ // the event for tab selection and context menu to work
37+ if (this .parent != null ) {
38+ Point pt = new Point (e .getXOnScreen (), e .getYOnScreen ());
39+ SwingUtilities .convertPointFromScreen (pt , this .parent );
40+ MouseEvent e1 = new MouseEvent (
41+ this .parent ,
42+ e .getID (),
43+ e .getWhen (),
44+ e .getModifiersEx (),
45+ (int ) pt .getX (),
46+ (int ) pt .getY (),
47+ e .getXOnScreen (),
48+ e .getYOnScreen (),
49+ e .getClickCount (),
50+ e .isPopupTrigger (),
51+ e .getButton ()
52+ );
53+ this .parent .dispatchEvent (e1 );
54+ }
55+ });
56+
3257 this .title = new JLabel (title );
3358 this .title .setToolTipText (tooltip );
59+ this .title .addMouseListener (mousePressedDispatcher );
60+
3461 this .ui .add (this .title );
3562
3663 // Adapted from javax.swing.plaf.metal.MetalTitlePane
@@ -52,6 +79,7 @@ public ClosableTabTitlePane(String title, String tooltip, Runnable onClose) {
5279 }
5380 }));
5481
82+ this .ui .addMouseListener (mousePressedDispatcher );
5583 this .ui .addMouseListener (new MouseAdapter () {
5684 @ Override
5785 public void mouseClicked (MouseEvent e ) {
@@ -60,31 +88,6 @@ public void mouseClicked(MouseEvent e) {
6088 }
6189 }
6290
63- @ Override
64- public void mousePressed (MouseEvent e ) {
65- // for some reason registering a mouse listener on this makes
66- // events never go to the tabbed pane, so we have to redirect
67- // the event for tab selection and context menu to work
68- if (ClosableTabTitlePane .this .parent != null ) {
69- Point pt = new Point (e .getXOnScreen (), e .getYOnScreen ());
70- SwingUtilities .convertPointFromScreen (pt , ClosableTabTitlePane .this .parent );
71- MouseEvent e1 = new MouseEvent (
72- ClosableTabTitlePane .this .parent ,
73- e .getID (),
74- e .getWhen (),
75- e .getModifiersEx (),
76- (int ) pt .getX (),
77- (int ) pt .getY (),
78- e .getXOnScreen (),
79- e .getYOnScreen (),
80- e .getClickCount (),
81- e .isPopupTrigger (),
82- e .getButton ()
83- );
84- ClosableTabTitlePane .this .parent .dispatchEvent (e1 );
85- }
86- }
87-
8891 @ Override
8992 public void mouseEntered (MouseEvent e ) {
9093 ClosableTabTitlePane .this .closeButton .setEnabled (true );
0 commit comments