Vassilis De
Vassilis De

Reputation: 373

Cardlayout doesn't appear panels inside cards on InternalFrame

I have a cardLayout used upon an InternalFrame

public class CardWindow extends InternalWindowTemplate{
    CardLayout cardLayout;
    private final JLabel label1, label2;
    private final JPanel panel1, panel2, cards, card1, card2;

    public CardWindow(){
        super("Elements", false, true, false, false,438,520);
        this.panel1= new JPanel(); 
        panel1.setBackground(Color.red);

        this.panel2= new JPanel();
        panel2.setBackground(Color.CYAN);

        this.label1= new JLabel("Label #1");
        panel1.add(label1);

        this.label2= new JLabel("Label #2");
        panel2.add(label2);

//        create first card
        this.card1 = new JPanel(); 
        card1.setBackground(Color.ORANGE);
        card1.add(panel1);
        card1.add(panel2);

    //        create second card
        this.card2 = new JPanel();
        card2.setBackground(Color.BLACK);
        label1.setText("1");
        label2.setText("2");
        card2.add(panel1);
        card2.add(panel2);

        this.cards = new JPanel();
        this.cardLayout = new CardLayout();
        cards.setLayout(cardLayout);
        cards.add(card1);
        cards.add(card2);

        addComponentToInternalWindow(cards);
}

The last statement is from my internal window abstract class

public abstract class InternalWindowTemplate{
//...
    public void addComponentToInternalWindow(Component component){
        setFlowLayout();
        getContainer().add(component);
    }
}

When I run it, I can see only the orange background from card1, but not the panels I added. Why is that?

Upvotes: 1

Views: 147

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209004

"When I run it, I can see only the orange background from card1, but not the panels I added. Why is that?"

A component can have one and only one parent. If a component is added to more than one container, only the last container it was added to will maintain the component.

That being said, you add panel1 and panel2 to card1. Then you add the same panel1 and panel2 to card2. So card2 is the winner. Since card1 is the first to be shown (as it was the first to be added), you will only see an empty card1 with the orange background

Upvotes: 1

Related Questions