简体   繁体   中英

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!

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.

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