Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a tab from a tab pane

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.

enter image description here

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.

like image 603
Harsha Avatar asked Nov 27 '25 17:11

Harsha


1 Answers

To remove tab use .remove(index) method of JTabbedPane. Learn more here: How to Use Tabbed Panes

like image 172
Harry Joy Avatar answered Nov 30 '25 05:11

Harry Joy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!