Close the tab with the click, not the currently selected JTabbedPane tab

I have this class inside my main class to close a button on my jTabbedPane. The problem is that, for example, I opened three tabs: the tab history, contact and upload, and the tab is the tab that is currently selected. When I try to close a log tab that is NOT a selected tab, the closing tab 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"));
+3
source share
2 answers

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

, , .

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);
    }
  });
  ...
}
+5

getSelectedComponent(), , , .

+1

All Articles