Reputation: 3578
I have created a swing application as bellow which shows main tasks in tabs when clicking the buttons which are related to specific tasks. I have added a small close button to each tab and what I need to to is close the tab when clicking the close button related to that tab.
The close button is in a class which is extended fron JPanel class as bellow,
public class CloseTab extends JPanel {
JLabel title = new JLabel();
JButton closeButton = new JButton();
int tabIndex;
JTabbedPane tabbedPane = null;
public static int SELECTED_TAB_INDEX;
.
.
.
public static void setSELECTED_TAB_INDEX(int SELECTED_TAB_INDEX) {
CloseTab.SELECTED_TAB_INDEX = SELECTED_TAB_INDEX;
}
.
.
public void setCloseAction(ActionListener al) {
closeButton.addActionListener(al);
closeButton.setSize(10, 10);
closeButton.setBorder(new EmptyBorder(0, 0, 0, 0));
closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ofm/mnu/icons/delete.gif")));
}
public void setTabIndex(int index) {
this.tabIndex = index;
System.out.println(tabIndex);
}
public void init() {
add(title);
add(closeButton);
setOpaque(false);
setCloseAction(closeActoion);
}
ActionListener closeActoion = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println(tabIndex);
if(tabbedPane.getTabCount() != 0 && tabbedPane.getSelectedIndex() == SELECTED_TAB_INDEX){
tabbedPane.remove(SELECTED_TAB_INDEX);
}
}
};
}
and in the main frame I seted the SELECTED_TAB_INDEX variable as follow,
tbpWorkSpace.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JTabbedPane a = (JTabbedPane) e.getSource();
CloseTab pnl = new CloseTab();
pnl.setSELECTED_TAB_INDEX(a.getSelectedIndex());
}
});
but, I couldn't get the result I wanted please tell me is there any other way to achieve the result I want.
Upvotes: 2
Views: 10323
Reputation: 2234
private void removeTabWithTitle(String tabTitleToRemove) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
String tabTitle = tabbedPane.getTitleAt(i);
if (tabTitle.equals(tabTitleToRemove)) {
tabbedPane.remove(i);
break;
}
}
}
Upvotes: 3
Reputation: 59650
To remove tab use .remove(index)
method of JTabbedPane. Learn more here: How to Use Tabbed Panes
Upvotes: 7