简体   繁体   中英

Close the clicked tab, not the currently selected tab 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"));

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.

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

And in Tab ...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM