编程语言
首页 > 编程语言> > java-JTabbedPane Tab组件的MouseEvent不会通过

java-JTabbedPane Tab组件的MouseEvent不会通过

作者:互联网

我有一个带有自定义标签组件的JTabbedPane.该组件包含一个JLabel(用于显示选项卡标题)和一个JButton(一个关闭按钮).当我更改JLabel中的文本时,JLabel停止接收鼠标事件,并且当我直接单击标签时,我无法再选择该选项卡,而是如果单击标签周围,则可以选择该选项卡.有任何想法吗?

一段代码:

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

解决方法:

我不记得在How to Use Tabbed Panes中讨论过的TabComponentsDemo中遇到过这样的问题.您可以将代码与该示例进行比较,以作为参考.

附录:将ButtonTabComponent重构为包含getLabel(),此版本的TabComponentsDemo中的runTest()会添加一个按钮,以表明所需的行为.特别是,每次按下按钮时,将重新绘制选项卡以显示放大的标题.

更新:在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);
}

标签:jtabbedpane,swing,jlabel,java
来源: https://codeday.me/bug/20191106/1999158.html