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

时间:2012-05-10 00:10:55

标签: java swing actionlistener jtabbedpane

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

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

这是我拨打标签的方式:

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

2 个答案:

答案 0 :(得分:5)

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

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

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

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

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

这里有更多背景信息:

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

在Tab ...

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

答案 1 :(得分:1)

如果要删除需要将日记选项卡组件传递给remove方法的日记选项卡,通过删除getSelectedComponent(),您将始终删除所选选项卡。

相关问题