关闭单击的选项卡,而不是当前选择的选项卡JTabbedPane

问题描述:

我的主类中有这个类,可以在jTabbedPane上放置一个关闭按钮。问题是,例如,我已经打开了三个选项卡:选项卡日志,联系人和上传,而选项卡联系人是当前选择的选项卡。当我尝试关闭不是选定标签的日记帐标签时,关闭的是当前选定的标签。

I have this class inside my main class to put a close button on my jTabbedPane. The problem is that, for example I have opened three tabs: tab journal, contact, and upload , and the tab contact is the currently selected tab. When I try to close the journal tab which is NOT the selected tab, the one that closes is the currently selected tab.

class Tab extends javax.swing.JPanel implements java.awt.event.ActionListener{
    @SuppressWarnings("LeakingThisInConstructor")
    public Tab(String label){
        super(new java.awt.BorderLayout());
        ((java.awt.BorderLayout)this.getLayout()).setHgap(5);
        add(new javax.swing.JLabel(label), java.awt.BorderLayout.WEST);
        ImageIcon img = new ImageIcon(getClass().getResource("/timsoftware/images/close.png"));
        javax.swing.JButton closeTab = new javax.swing.JButton(img);
        closeTab.addActionListener(this);
        closeTab.setMargin(new java.awt.Insets(0,0,0,0));
        closeTab.setBorder(null);
        closeTab.setBorderPainted(false);
        add(closeTab, java.awt.BorderLayout.EAST);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        closeTab();    //function which closes the tab          
    }

}

private void closeTab(){
    menuTabbedPane.remove(menuTabbedPane.getSelectedComponent());
}

这就是我所说的选项卡:

This is what I do to call the tab :

menuTabbedPane.setTabComponentAt(menuTabbedPane.indexOfComponent(jvPanel), new Tab("contactPanel"));


您的 actionPerformed()方法调用您的 closeTab()方法。您的 closeTab()方法从选项卡式窗格中删除当前选择的选项卡

Your actionPerformed() method calls your closeTab() method. Your closeTab() method removes the currently selected tab from the tabbed pane.

相反,您需要使用单击的按钮删除与选项卡相对应的组件。

Instead, you need to remove the component that corresponds to your tab with the button that was clicked.

创建 Tab $ c时$ c>,还将作为选项卡窗格内容的组件传递给构造函数。然后,可以在 actionPerformed()方法中使用它,并将组件传递给 closeTab()

When you create your Tab, also pass into the constructor the component that is the tab pane content. Then, you can use that in your actionPerformed() method, and pass the component to closeTab()

public void actionPerformed(ActionEvent e)
{
  closeTab(component);
}

private void closeTab(JComponent component)
{
  menuTabbedPane.remove(component);
}

这里还有更多背景信息:

Here's a bit more context:

tab = new Tab("The Label", component);          // component is the tab content
menuTabbedPane.insertTab(title, icon, component, tooltip, tabIndex);
menuTabbedPane.setTabComponentAt(tabIndex, tab);

在选项卡中...

public Tab(String label, final JComponent component)
{
  ...
  closeTab.addActionListener(new ActionListner()
  {
    public void actionPerformed(ActionEvent e)
    {
      closeTab(component);
    }
  });
  ...
}