I want to build a tabbed interface in JAVA, with close button on each tab. For that I have used the following class: ButtonTabComponent
I have a button on my GUI whi
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;
}