user3186034
user3186034

Reputation: 43

Java reorder tabs in JTabbedPane

My problem is that I need to set the tab which gets clicked on , to be the left most tab in JTabbedPane. What method would i need to use to accomplish this?

Upvotes: 1

Views: 586

Answers (2)

Amber
Amber

Reputation: 2463

You'll need to add a ChangeListener so you know when the tab has been selected. Then you can use the methods in JTabbedPane to remove and reinsert at a particular index.

tabbedPane.addChangeListener(new ChangeListener() {

        // you need this so you can ignore ChangeEvents as you're removing & inserting panes
        boolean listening = true;

        @Override
        public void stateChanged(ChangeEvent e)
        {
            int index = tabbedPane.getSelectedIndex();
            if (listening && index != 0)
            {
                listening = false;
                // get whatever info you need to recreate the tab
                String title = tabbedPane.getTitleAt(index);
                Component component = tabbedPane.getTabComponentAt(index);
                // remove the old tab
                tabbedPane.removeTabAt(index);
                // insert the new one in the correct place
                tabbedPane.insertTab(title, null, component, null, 0);
                // select the current tab
                tabbedPane.setSelectedIndex(0);
                listening = true;
            }
        }
    });

Upvotes: 1

tomse
tomse

Reputation: 501

Try the following JTabbedPane methods:

// get tab at mouse position
indexAtLocation(int x, int y)
// or get the selected tab
int getSelectedIndex()
// remove the tab at the determined index ...
removeTabAt(int index)
// ... and add it at a new one
insertTab(String title, Icon icon, Component component, String tip, int index)

Upvotes: 0

Related Questions