MouseEvents for JTabbedPane tab component do not leak through

I have JTabbedPanewith custom component tabs. This component contains JLabel(to display the tab title) and JButton(close button). When I change the text in JLabel, it JLabelstops receiving mouse events, and I can no longer select this tab, when I click on the label directly, if I click on the shortcut, then I can select the tab. Any ideas?

Code snippet:

class ShellPanelTabComponent extends JPanel implements ActionListener{

    private ShellPanel panel;
    private JLabel label;

    public ShellPanelTabComponent(final ShellPanel panel){
      super(new FlowLayout(FlowLayout.LEFT, 0, 0));
      this.panel = panel;
      setOpaque(false);

      label = new JLabel(panel.getTitle());
      label.setFocusable(false);
      add(label);
      label.setBorder(BorderFactory.createEmptyBorder(2,0,0,5));

      //now the button
      CloseButton closeButton = new CloseButton(panel);
      add(closeButton);
      closeButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae) {
      panel.getShell().removeShellPanel(panel);
    }

    /**
     * @return the label
     */
    public JLabel getLabel() {
      return label;
    }
  }
+3
source share
3 answers
0

, ​​ TabComponentsDemo, . .

: ButtonTabComponent getLabel(), runTest() TabComponentsDemo , . , , , , .

: pane.remove().

public void runTest() {
    pane.removeAll();
    for (int i = 0; i < tabNumber; i++) {
        final int titleIndex = i;
        String title = "Tab " + titleIndex;
        final JButton button = new JButton("Relabel tab");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int index = pane.indexOfComponent(button);
                ButtonTabComponent btc = (ButtonTabComponent)
                    pane.getTabComponentAt(index);
                JLabel label = btc.getLabel();
                pane.setTitleAt(index, label.getText() + titleIndex);
                label.invalidate();
                pane.repaint();
            }
        });
        pane.add(title, button);
        initTabComponent(i);
    }
    tabComponentsItem.setSelected(true);
    pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
    scrollLayoutItem.setSelected(false);
    this.setPreferredSize(new Dimension(500, 200));
    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}
+2

It seems that I remember this question recently, although I can not find the wiring. I believe the problem is that the "custom component" receives the mouse event, so it is not passed to the tabbed panel. It was suggested to use the dispatchEvent (...) method to retransmit the mouse event to the appropriate tab.

+2
source

Source: https://habr.com/ru/post/1752649/


All Articles