急求java CardLayout的使用方法,实现图片第一张,上一张,下一张的代码? 120

 我来答
百度网友1f0ad9f
2019-11-19 · 超过131用户采纳过TA的回答
知道小有建树答主
回答量:248
采纳率:72%
帮助的人:111万
展开全部
package chapter24;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Eg_02 extends JFrame{
private CardLayout cardLayout = new CardLayout();;
JPanel panel = new JPanel(cardLayout);

public Eg_02() {
this.setTitle("使用卡片布局管理器");
this.setBounds(100, 100, 650, 200);

// System.out.println(this.getContentPane()==this.getRootPane().getContentPane());//print:true
// this.add(panel, BorderLayout.CENTER);

this.getContentPane().add(panel, BorderLayout.CENTER);
String[]labelNames = {"卡片A", "卡片B", "卡片C", "卡片D"};
for (int i = 0; i < labelNames.length; i++) {
final JLabel label = new JLabel(labelNames[i]);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("", Font.BOLD, 18));
label.setForeground(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
panel.add(label, labelNames[i]);
}

final JPanel btnPanel = new JPanel();
this.getContentPane().add(btnPanel, BorderLayout.SOUTH);
String[]btnNames = {"第一个", "前一个", "卡片A", "卡片B", "卡片C", "卡片D", "后一个", "最后一个"};
for (int i = 0; i < btnNames.length; i++) {
JButton btn = new JButton(btnNames[i]);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String btnText = btn.getText();
switch (btnText) {
case "第一个":
cardLayout.first(panel);
break;
case "前一个":
cardLayout.previous(panel);
break;
case "卡片A":
cardLayout.show(panel, "卡片A");
break;
case "卡片B":
cardLayout.show(panel, "卡片B");
break;
case "卡片C":
cardLayout.show(panel, "卡片C");
break;
case "卡片D":
cardLayout.show(panel, "卡片D");
break;
case "后一个":
cardLayout.next(panel);
break;
default:
cardLayout.last(panel);
break;
}
}
});
btnPanel.add(btn);
}

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}

public static void main(String[] args) {
new Eg_02();
}

}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式