这是一个简单的程序,说明了CardLayout用于所需任务的用法。您可能还想看看这篇文章(从 2005 年开始,所以有些事情可能已经改变)。
import java.awt.*;
import javax.swing.*;
public class CardLayoutTestApplet extends JApplet {
@Override
public void init() {
final Container pane = getContentPane();
final CardLayout paneLayout = new CardLayout();
JPanel panel1 = new JPanel();
JButton button1 = new JButton("Next>>");
panel1.add(button1);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
paneLayout.show(pane, "Card2");
}
});
JPanel panel2 = new JPanel();
panel2.add(new JLabel("Second Panel"));
pane.setLayout(paneLayout);
pane.add(panel1, "Card1");
pane.add(panel2, "Card2");
}
}