19

嗨,如果这已经发布,我很抱歉,但我仔细看了看,发现了其他我不太理解的代码。我是 Java 编程的新手,希望有人指出我如何通过按下按钮更改为所需面板的正确方向。任何帮助将不胜感激。我只是想完全理解这个概念是如何工作的。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;  // Packages used in this program imported    

public class onlineGame extends JFrame implements ActionListener
{

    JPanel cards;
    JButton button1, button2, button3;

    public onlineGame() //This is the CONSTRUCTOR method
    {
        //The entry point into your program
        setLayout(new FlowLayout()); //Use this for now.
        setSize(810, 510); //Set the size of the JFrame
        setTitle("Generic Card Game"); //Put Title on top of JFrame
        setBackground(Color.yellow);
        setResizable(false);

        button1 = new JButton("THIS IS BUTTON 1");
        button2 = new JButton("THIS IS BUTTON 2");
        button3 = new JButton("THIS IS BUTTON 3");

        button1.addActionListener(this);
        button2.addActionListener(this);
        button3.addActionListener(this);    

        //Create the cards

        JPanel card1 = new JPanel();
        card1.add(button1);

        JPanel card2 = new JPanel();
        card2.add(button2);

        JPanel card3 = new JPanel();
        card3.add(button3);

        //Create the panel that contains the "cards".

        cards = new JPanel(new CardLayout());

        cards.add(card1);
        cards.add(card2);
        cards.add(card3);

        getContentPane().add(cards); 
        setVisible(true); //Make JFrame visible
    }

    public void actionPerformed(ActionEvent e)
    {    
        if (e.getSource() == button1){    
            //What do i put here to change to Panel card2 or card3 and so on.
        }
    }
    public static void main(String args[])
    {    
        new onlineGame(); // This calls the constructor and runs it    
    }
}
4

1 回答 1

37

要切换到任意面板,请确保在添加卡片组件时指定约束:

cards.add(card1, "Card 1");
cards.add(card2, "Card 2");
cards.add(card3, "Card 3");

然后翻转到不同的组件:

CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.show(cards, "Card 2");

要导航到下一个组件,您可以使用:

cardLayout.next(cards);

阅读:卡片布局

于 2013-02-11T22:23:01.187 回答