orgillion
orgillion

Reputation: 3

JPanel inside a JPanel inside a JTabbedPane doesn't show up

I have a JPanel (firstPanel) which is embedded into an other JPanel (secondPanel). I want to create a JTabbedPane with two tabs: one for the firstPanel and one for the secondPanel. However, when I switch to secondPanel, the embedded firstPanel won't show up.

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;


public class Application extends JFrame
{   
    public Application()
    {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(300, 300));


        JPanel firstPanel = new JPanel();
        firstPanel.add(new JLabel("first"));

        JPanel secondPanel = new JPanel();

//      JPanel thirdPanel = new JPanel();
//      thirdPanel.add(new JLabel("third"));
//
//      secondPanel.add(thirdPanel);
        secondPanel.add(firstPanel);
        secondPanel.add(new JLabel("second"));

        JTabbedPane mainPanel = new JTabbedPane();
        mainPanel.addTab("First", firstPanel);
        mainPanel.addTab("Second", secondPanel);

        this.add(mainPanel);
    }


    public static void main(String[] args) 
    {
        Application app = new Application();
        app.pack();
        app.setVisible(true);
    }

}

When I add the thirdPanel instead of the first, it works as expected. Am I missing something obvious? Thanks you!

Upvotes: 0

Views: 168

Answers (1)

Joe C
Joe C

Reputation: 15684

This is because you are trying to add a single panel to two different parents, one being your secondPanel, and the other being your tab. You can't do that.

Can I ask why you think you want to do this? There is probably a better solution out there for you.

Upvotes: 4

Related Questions