Cardlayout不会在InternalFrame上的卡片内显示面板

时间:2014-07-10 11:25:56

标签: java swing jpanel cardlayout

我在InternalFrame上使用了cardLayout

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

最后一个语句来自我的内部窗口抽象类

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

当我运行它时,我只能看到来自card1的橙色背景,但不能看到我添加的面板。那是为什么?

1 个答案:

答案 0 :(得分:1)

  

“当我运行它时,我只能看到来自card1的橙色背景,但不能看到我添加的面板。为什么会这样?”

一个组件可以有一个,只有一个父组件。如果将组件添加到多个容器中,则只添加它的最后一个容器将维护该组件。

话虽如此,您将panel1panel2添加到card1。然后,将相同的panel1panel2添加到card2。所以card2是赢家。由于card1是第一个被显示的(因为它是第一个被添加),因此您只会看到一个带有橙色背景的空card1

相关问题