简体   繁体   中英

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?

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;
            }
        }
    });

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM