Java开发GUI之CardLayout卡片布局
CardLayout布局允许进行多套界面的设计,通过切换界面来实现布局样式的改变。CardLayout类似与一叠卡片,默认最先添加的在前面,界面始终只展示一个卡片。示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   | static Panel cardPannel;
  static void CardLayoutTest(){     Frame frame = new Frame("Label");     Panel top = new Panel();     Choice choice = new Choice();     choice.add("BUTTON");     choice.add("LABEL");     choice.addItemListener(new CardLayoutChoiceListener());     top.add(choice);          CardLayout layout = new CardLayout();     cardPannel = new Panel(layout);     Panel p1 = new Panel();     p1.add(new Button("one"));     p1.add(new Button("two"));     p1.add(new Button("three"));     cardPannel.add("BUTTON", p1);     Panel p2 = new Panel();     p2.add(new Label("label"));     p2.add(new Label("label"));     p2.add(new Label("label"));     cardPannel.add("LABEL", p2);     top.add(cardPannel);          frame.add(top);     frame.pack();     frame.show(); }
   | 
 
Choice的监听对象类如下:
1 2 3 4 5 6 7 8 9
   | class CardLayoutChoiceListener implements ItemListener{
      @Override     public void itemStateChanged(ItemEvent e) {                  ((CardLayout)APP.cardPannel.getLayout()).show(APP.cardPannel, (String) e.getItem());     }      }
  | 
 
需要注意,CardLayout在进行卡片切换时,是通过卡片名来确定的,所以上面的代码将Choice的标题设置为和卡片的名称一致。
                  
CardLayout类中方法总结如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   |  public CardLayout();
  public CardLayout(int hgap, int vgap);
  public int getHgap();
  public void setHgap(int hgap);
  public int getVgap();
  public void setVgap(int vgap);
  public void first(Container parent);
  public void next(Container parent);
  public void previous(Container parent);
  public void last(Container parent);
  public void show(Container parent, String name);
 
  |