1.作用:
卡片布局管理器是管理器的一种,卡片布局能够让多个组件共享同一个显示空间,共享空间的组件之间的关系就像一叠牌,组件叠在一起,初始时显示该空间中第一个添加的组件,通过CardLayout类提供的方法可以切换该空间中显示的组件。
2.CardLayout的常用构造方法:
void first(Container parent) 翻转到指定容器的第一张卡片
void next(Container parent) 翻转到指定容器的下一张图片
void previous(Container parent) 翻转到指定容器的上一张图片
void last(Container parent) 翻转到指定容器的最后一张图片
void show(Container parent,String name) 显示指定卡片
3.卡片布局管理器的用法
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.lovo.game.MediaTrackerHelp;
public class CardLayoutTest extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private MediaTracker mediaTracker;
private Image[] images = new Image[10];
private CardLayout cardLayout;
private JPanel showImgPnl;
private JTextField page;
public CardLayoutTest() {
setTitle("卡片布局管理器");
setSize(500, 500);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 创建MediaTracker对象
mediaTracker = new MediaTracker(this);
// 添加10张图像到媒体追踪器的图像列表中
for (int i = 0; i < images.length; i++) {
// 将图像添加到追踪器列表中
images[i] = MediaTrackerHelp.addImage(mediaTracker, new ImageIcon(
"images/" + i + ".JPG").getImage());
}
/* 添加按钮 */
JButton previous = new JButton("previous");
JButton next = new JButton("next");
page = new JTextField("5");
JButton go = new JButton("go");
JPanel btnPnl = new JPanel();
btnPnl.add(previous);
btnPnl.add(next);
btnPnl.add(page);
btnPnl.add(go);
next.addActionListener(this);
previous.addActionListener(this);
go.addActionListener(this);
this.add(btnPnl, BorderLayout.SOUTH);
/* 创建卡片布局管理器 */
cardLayout = new CardLayout();
showImgPnl = new JPanel(cardLayout);
/* 将10张图像添加到使用卡片布局管理器的容器中 */
for (int i = 0; i < images.length; i++) {
final Image image = images[i];
JPanel imgPnl = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 100, 100, null);
}
};
showImgPnl.add("img" + i, imgPnl);
}
this.add(showImgPnl, BorderLayout.CENTER);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("previous".equals(cmd)) {
cardLayout.previous(showImgPnl);
} else if ("next".equals(cmd)) {
cardLayout.next(showImgPnl);
} else if ("go".equals(cmd)){
String page = this.page.getText();
cardLayout.show(showImgPnl, "img" + page);
}
}
public static void main(String[] args) {
new CardLayoutTest();
}
}