Java 尝试使用卡片布局,但无法使显示工作

Java 尝试使用卡片布局,但无法使显示工作,java,cardlayout,Java,Cardlayout,我尝试使用卡片布局,我在顶部有两个按钮,用于选择更改卡片,但由于某些原因,它不起作用,下一个方法起作用,但show或first\last不起作用,当然我不能使用next,因为我希望每个按钮都有一张特定的卡片,下面是我的代码: cards = new CardLayout(); cardPanel = new JPanel(); cardPanel.setLayout(cards); cards.show(cardPanel, "gapas"); JPa

我尝试使用卡片布局,我在顶部有两个按钮,用于选择更改卡片,但由于某些原因,它不起作用,下一个方法起作用,但show或first\last不起作用,当然我不能使用next,因为我希望每个按钮都有一张特定的卡片,下面是我的代码:

     cards = new CardLayout();
    cardPanel = new JPanel();
    cardPanel.setLayout(cards);
    cards.show(cardPanel, "gapas");

    JPanel firstCard = new JPanel();
    firstCard.setBackground(Color.WHITE);;


    JPanel secondCard = new JPanel();
    secondCard.setBackground(Color.blue);


    cardPanel.add(firstCard, "kalam");
    cardPanel.add(secondCard, "gapan");

    guiFrame.add(tabsPanel,BorderLayout.NORTH);
    guiFrame.add(cardPanel,BorderLayout.CENTER);
    guiFrame.setVisible(true);
}

ActionListener action = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().matches("kalam")){
            cards.show(cardPanel,"kalam");
            System.out.println("kalam");
        }
        else{
            cards.show(cardPanel, "gapas");
            System.out.println("gapas");
        }

    }
};
文件规定: show(容器父级,字符串名称)使用addLayoutComponent方法翻转到使用指定名称添加到此布局的组件

添加两项:

  • 卡拉姆
  • 加潘
但你试图表现出来:gapas


另外,我会先添加,然后再尝试2个节目。

我想你想要这样的节目

public class TestCard extends JFrame implements ActionListener {

CardLayout cards;
JPanel cardPanel, tabsPanel;
JButton b1, b2;

public TestCard() {
    b1= new JButton("kalam");
    b2= new JButton("gapas");
    tabsPanel = new JPanel();
    cards = new CardLayout();
    cardPanel = new JPanel();
    cardPanel.setLayout(cards);

    JPanel firstCard = new JPanel();
    firstCard.setBackground(Color.WHITE);


    JPanel secondCard = new JPanel();
    secondCard.setBackground(Color.blue);


    cardPanel.add(firstCard, "kalam");
    cardPanel.add(secondCard, "gapas");
    tabsPanel.add(b1);
    tabsPanel.add(b2);

    add(tabsPanel, BorderLayout.NORTH);
    add(cardPanel, BorderLayout.CENTER);
    b1.addActionListener(this);
    b2.addActionListener(this);
    setSize(800, 600);

    cards.show(cardPanel, "gapas");
    setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().matches("kalam")) {
        cards.show(cardPanel, "kalam");
        System.out.println("kalam");
    } else {
        cards.show(cardPanel, "gapas");
        System.out.println("gapas");
    }
}
public static void main(String[] args) {
    new TestCard();
}
}

您需要创建并发布http:/sscce.org。