JTabbedPane - tab with close button reference

 ̄綄美尐妖づ 提交于 2019-11-29 16:41:08

The error lies in the call

pane.setTabComponentAt(PanelCounter, new ButtonTabComponent(pane, this));

You don't want to add the button to the tab index PanelCounter but to the one just created. Its index can be obtained using getTabCount(), which of course at this point is one too high, hence:

pane.setTabComponentAt(pane.getTabCount()-1, new ButtonTabComponent(pane, this));

I was checking your code and I could accomplish using

pane.remove(pane.getSelectedComponent());

in the actionPerformed method.

Here I am creating JTabbedPane tabs, with a close button for each tab. When the close button is clicked, only the respective tab closes.

//This is where a tab is created in some other function of same class
jtp.addTab("Create",new JPanel());  //jtp is a global JTabbedPane variable
int index = jtp.indexOfTab("Create");
jtp.setTabComponentAt(index,createTabHead("Create"));   

public JPanel createTabHead(String title)
{
    final String st=title;
    JPanel pnlTab = new JPanel();
    pnlTab.setLayout(new BoxLayout(pnlTab,BoxLayout.LINE_AXIS));
    pnlTab.setOpaque(false);
    JButton btnClose = new JButton("x");
    JLabel lblTitle = new JLabel(title+"    ");
    btnClose.setBorderPainted(false);
    btnClose.setOpaque(false);

    btnClose.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             int i; 
            for(i=0;i<=jtp.getTabCount()-1;i++)//To find current index of tab
            {
            if(st.equals(jtp.getTitleAt(i)))
                    break;
            }                   
               jtp.removeTabAt(i);
             }
            });

     pnlTab.add(lblTitle);
    pnlTab.add(btnClose);
    return pnlTab;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!