Alvins
Alvins

Reputation: 887

Change JTabbedPane component on select tab

I've got a JTabbedPane and i need to substitute tab 1 component when user select it. I can't directly add the right component at application start because i don't have full data to generate it.

I need something like this:

    int tabTochange = 1;
    tabbedPane.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (tabbedPane.getSelectedIndex() == tabTochange)
            {
                JComponent component = generataComponent();
                tabbedPane.removeTabAt(tabTochange); // Remove old tab
                // add new one
                tabbedPane.insertTab("title", null, component, "tip", tabTochange);

            }
        }
    });

But this code doesn't work, it removes the tab other tabs after tab 1 and duplicate it.

Upvotes: 2

Views: 3864

Answers (3)

kyul
kyul

Reputation: 46

If tab1 has an index of 1, and tab2 has an index of 2. After you remove tab1, wouldn't tab2 now have an index of 1? So, when you go to add a new tab with an index of 1, it won't work. Maybe there is a way of just changing tab1.

Also, each tab should contain a JPanel, so it might be worth just changing the relevant JPanel, and the tab's title text.

I know this doesn't completely answer your question, but I don't think I have enough points to just put it as a comment. Hope this helps :)

Upvotes: 0

trashgod
trashgod

Reputation: 205805

Instead of removeTabAt() and insertTab(), use getComponentAt(tabTochange) or getSelectedComponent() to get a reference the component. Update the component as required, perhaps using CardLayout.

Upvotes: 3

mKorbel
mKorbel

Reputation: 109813

  • I think that JTabbedPane / CardLayout was developed as static GUI without add/remove/modify Tabs/Cards, not to change number, orders, numbers of Tabs/Cards on runtime, even though it is possible

  • you would need to solve bunch of side effects, to hold tabs (indexing and its JComponents ) in secondary array

  • put JList (JTree depends of structure) on left side of JFrame, create a JPanel to each of Items/Nodes, put these JPanels to CardLayout, add proper List(Tree)SelectionListener, then selection from mouse/keyboard will firing switch between card, nothing in this stucture is dynamic (except value in JComponents), everything is prepared on GUI startup

Upvotes: 2

Related Questions