CardLayout方法show()在awt

时间:2015-12-15 02:23:15

标签: java layout awt

我正在尝试CardLayout,但不知道为什么show()的{​​{1}}无效。我收到了错误。

CardLayout

我在运行此错误时只得到一个空白框架。

package java_files;

import java.awt.*;
import java.awt.event.*;

//import javax.swing.JButton;

public class AwtLayoutExample  {
   public static void main(String args[])
   {
      Frame f=new Frame("Card Layout");
      f.setSize(400,400);
      f.setVisible(true);
      f.addWindowListener(new WindowAdapter(){
          public void windowClosing(WindowEvent e){
              System.exit(0);
          }
      });
      CardLayout card=new CardLayout();
      f.setLayout(card);
      Panel panelCont=new Panel();
      Panel panelFirst=new Panel();
      Panel panelSecond=new Panel();
      Button b1=new Button("Switch to 2nd Panel");
      Button b2=new Button("Switch to 1st Panel");
      panelFirst.add(b1);

      panelSecond.add(b2);
      panelFirst.setBackground(Color.CYAN);
      panelSecond.setBackground(Color.GREEN);
      panelCont.add(panelFirst,"1");
      panelCont.add(panelSecond, "2");
      card.show(panelCont, "1");      
      b1.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
      card.show(panelCont, "2");
      }
      });
      b2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
              card.show(panelCont, "2");
          }
      });
      f.add(panelCont);
      f.pack();
      f.setVisible(true);
   }
}   

1 个答案:

答案 0 :(得分:0)

您可以将CardLayout应用于Panel,然后将其他Panel添加到此Panel

Panel panelCont=new Panel(new CardLayout());
panelCont.add("one", panelOne);
panelCont.add("two", panelTwo);
panelCont.add("three", panelThree);

当你表演时你可以这样做:

((CardLayout) panelCont.getLayout()).show(panelCont, "two");