在一些特定的条件下可能会用到卡片布局,虽然它不是一种特别重要的布局,但是在完成一些特殊的功能时比较好用。比如模拟幻灯片的例子,单击不同的按钮,出现相应的变换图片
卡片布局管理器中的组件就像是幻灯片中的图片,每次只能看一张,但单击不同按钮会看到不同的图片
卡片布局可以添加多个组件,但同一时刻只能看见其中一个组件
CardLayout类的构造方法
public CardLayout() :创建一个卡片布局管理器
public CardLayout(int hgap,int vgap) :创建具有指定水平间距和垂直间距的卡片布局管理器
CardLayout类常用的方法
public void first(Container parent) :切换到容器第一张
public void last(Container parent) :切换到容器最后一张
public void next(Container parent):切换到当前容器的下一张
public void previous(Container parent): 切换到当前容器的上一张
public void show(Container parent,String name):切换到指定名称的组件
注意:show方法中的name即组件名称,如果指定的名称不存在,既不会报错,也不会出错
代码实例:
package ch9;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutTest extends JFrame implements ActionListener
{
JButton next = new JButton("下一张");
JButton previous = new JButton("前一个");
JButton first = new JButton("第一个");
JButton second = new JButton("第二个");
JButton third = new JButton("第三个");
JButton last = new JButton("最后一个");
private JButton[] jb = new JButton[]{next,previous,first,second,third,last};
private JPanel jp = new JPanel();
public CardLayoutTest()
{
this.setLayout(null); //此处设置空布局,按钮直接被放入窗体内,不用布局管理器
for(int i=0;i<jb.length;i++)
{
jb[i].setBounds(300,30+30*i,90,20);//设置按钮添加到窗体内
this.add(jb[i]);
jb[i].addActionListener(this);
}
jp.setLayout(new CardLayout());
for(int i=0;i<4;i++)
{
jp.add(new Card(i),"card"+(i+1));
}
jp.setBounds(10,10,200,200);
this.add(jp);
this.setTitle("卡片布局管理器");
this.setBounds(200,200,400,250);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent a)
{
CardLayout cl = (CardLayout) jp.getLayout(); //获取卡片布局管理器引用
if(a.getSource()==jb[0])
{
cl.next(jp);
}
else if(a.getSource()==jb[1])
{
cl.previous(jp);
}
else if(a.getSource()==jb[2])
{
cl.first(jp);
}
else if(a.getSource()==jb[3])
{
cl.show(jp,"card2");
}
else if(a.getSource()==jb[4])
{
cl.show(jp,"card3");
}
else if(a.getSource()==jb[5])
{
cl.last(jp);
}
}
public static void main(String args[])
{
new CardLayoutTest();
}
}
class Card extends JPanel //自定义卡片类
{
int index,R;
public Card(int index)
{
this.index = index + 1;
this.R = index *20+20;
}
public void paint(Graphics g) //绘图
{
g.clearRect(0, 0, 200, 200);
g.drawString("下面是第"+index+"图片",80,20);
g.setColor(new Color(40,40,40));
g.fillRect(125-R,125-R,R*2,R*2);
g.setColor(new Color(205,205,205));
g.fillOval(125-R,125-R,R*2,R*2);
}
}