up.addActionListener(this);
next.addActionListener(this);
go.addActionListener(this);
this.add(jp, BorderLayout.SOUTH);
/* 创建使用CardLayout布局管理器的容器 */
cardLayout = new CardLayout();
jPanel = new JPanel(cardLayout);
/* 向面板中添加几张图片 */
// 将图片绘制到面板中 /
JPanel images = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(
Toolkit.getDefaultToolkit().getImage(
"src/images/sprite.png"), 200, 100, this);
}
};
// 将图片面板添加到使用了cardLayout容器面板中
jPanel.add("sprite", images);
JPanel img = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(
Toolkit.getDefaultToolkit().getImage(
"src/images/Freedom1.gif"), 200, 100, this);
}
};
jPanel.add("Freedom1", img);
JPanel im = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(
Toolkit.getDefaultToolkit().getImage(
"src/images/sprite1.png"), 200, 100, this);
}
};
jPanel.add("sprite1", im);
// 将使用了CardLayout的面板添加到窗体中显示
this.add(jPanel, BorderLayout.CENTER);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("下一张".equals(cmd)) {
cardLayout.next(jPanel); // 切换下一个选项卡
} else if ("上一张".equals(cmd)) {
cardLayout.previous(jPanel);// 切换上一个选项卡
} else if ("go".equals(cmd)) {
cardLayout.show(jPanel, "Freedom" + jTextField.getText());//这个主要是用于名字相似的图片,如果你想跳转的图片名字不一样的话,你就可以去把图片的名字改成相似的。
}
}
public static void main(String[] args) {
new CardLayoutDemo2();
}
}
运行效果: