- 0
- 0
- 约1.45万字
- 约 6页
- 2016-10-09 发布于贵州
- 举报
java课程设-拼图游戏代码
package love;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class Games extends JFrame implements ActionListener {
private JButton buttons[][];// 存储按键的数组
private Container container;// 一个容器
private GridLayout layout;// 布局方式为GridLayout
private int count = 0, is[] = new int[8];// count的作用是计算按键移动的次数,is[]储存一个随机产生的1到8数字数组
public Games() {
super(拼图游戏);// 设置标题
layout = new GridLayout(3, 3);// 3行3列
container = getContentPane();// 该容器的布局方式,及其重要,否则产生空引用异常
container.setLayout(layout);// 将该布局方式作用于容器
buttons = new JButton[3][3];// 给按键数组分配储存空间
int locate1, locate2;// locate1用来指示当前产生的元素 locate2用来指示locate1之前的元素
for (locate1 = 0; locate1 8; locate1++) {// 该方法作用是产生1到8这8个数,随机分配给数组,即无序排列
int g = new Random().nextInt(8) + 1;// 随机产生一个空白按键,即不显示的那个
is[locate1] = g;
for (locate2 = locate1 - 1; 0 = locate2; locate2--) {
if (is[locate1] == is[locate2])
break;
}
if (locate2 != -1)
locate1--;
}
int temp = 0;
int r = new Random().nextInt(3);// 随机产生一个0到3的数,代表空白按键的行
int l = new Random().nextInt(3);// 随机产生一个0到3的数,代表空白按键的列
for (int i = 0; i 3; i++) {
for (int j = 0; j 3; j++) {
if (r == i l == j) {// 空白按键设置为9,不显示
buttons[i][j] = new JButton(9);
container.add(buttons[i][j]);
buttons[i][j].setVisible(false);
} else {
buttons[i][j] = new JButton( + is[temp++]);// 将数组数组的值作为显示的8个按键的名字
container.add(buttons[i][j]);
}
buttons[i][j].addActionListener(this);// 注册监听事件
}
}
setSize(300, 300);// 设置显示容器区域大小
setVisible(true);
}
public void actionPerformed(ActionEvent event) {// 事件处理,由于计算量小该处将所有按键单独分析
JButton b = (JButton) event.getSource();
if (b == buttons[0][0]) {
if (buttons[0][1].getText().equals(9)) {
buttons[0][1].setText( + buttons[0][0].getText());
buttons[0][1].setVisible(true);
buttons[0][0].setText(9);
buttons[0][0].s
您可能关注的文档
最近下载
- 生猪无针注射器产品技术标准.pdf VIP
- 无人机测绘技术与应用课件12--正射相机组成及特点.ppt
- 儿童水电解质代谢紊乱与液体疗法(与“腹泻”有关文档共73张).pptx VIP
- 广东广州外国语学校2023年化学高一上期末综合测试模拟试题含解析.doc VIP
- 一种全氟异丁腈粗气中高含量酸性杂质的去除方法.pdf VIP
- 模具报价表模板.xls VIP
- 2025年租房合同范本(可直接打印)与租房合同范本(标准版) .pdf VIP
- 重症凝血病标准化评估中国专家共识2025解读.pptx
- 南昌印钞有限公司2026年度招聘备考题库【11人】精编答案详解.docx VIP
- 小学语文课程标准与教材研究教材配套教学课件(完整版)(文字可修改版).pptx VIP
原创力文档

文档评论(0)