这次写了一个拼图的程式(旁边有练习Thread用的小汽车),但是一直没有显示视窗出来。
在放入System.out.println("test"); 的方式后,
有找到问题出在生产不重复乱数的方法内,
但想了很久还是不知道如何解决,
所以只好拜托各位帮我看看了!
(乱数方法在82行)
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
class CMoveCar implements Runnable{
private JLabel car;
private int car_x=0, car_y, time, wide;
public CMoveCar(JLabel c,int y, int t, int w){
car = c;
car_y = y;
time = t;
wide = w;
}
public void run(){
car.setLocation(car_x, car_y);
while(true){
System.out.println("test");
car_x += 2;
car.setLocation(car_x, car_y);
Pause(time);
if(car_x >= wide){
car_x = 0;
car.setLocation(0, car_y);
}
}
}
private void Pause(int t){
try{
Thread.sleep(t);
}
catch(InterruptedException o){}
}
}
class Cpuzzle extends JFrame{
//乱数用
int minx = 0, max = 8;
int[] num = new int[9];
//其余物件
int k = 0;
JLabel[] picPuzzle = new JLabel[9];
JLabel picCar = new JLabel(new ImageIcon("car.png"));
JLabel success = new JLabel("成功!");
ImageIcon[] pic = new ImageIcon[9];
int pressT=0, press1 = -1, press2 = -1;
CPuzzMAdapter listener = new CPuzzMAdapter();
Cpuzzle(){
randomOut(minx, max, num); //生成乱数存于阵列
//载入图片
for(int i = 0; i<pic.length; i++){
pic[i] = new ImageIcon(i+".jpg");
}
//载入拼图
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
picPuzzle[k] = new JLabel(pic[num[k]]);
picPuzzle[k].setBounds(100+100*j,100+100*i,100,100);
add(picPuzzle[k]);
picPuzzle[k].addMouseListener(listener);
k++;
}
}
picCar.setSize(100,50);
add(picCar);
Thread car = new Thread(new CMoveCar(picCar, 400, 100, 500));
car.start();
success.setBounds(200,400,100,50);
setTitle("拼图游戏");
setLayout(null);
setBounds(100,100,500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void randomOut(int minx, int max, int[] data){
Random ran = new Random();
boolean pass;
int num;
for(int i = 0; i<data.length; i++){
while(true){
pass = true;
num = ran.nextInt(max)+minx;
for(int j = 0; j<data.length; j++){
if(data[j] == num){
pass = false;
break;
}
}
if(pass){
data[i] = num;
break;
}
}
}
}
//事件处理
class CPuzzMAdapter extends MouseAdapter{
public void mouseClicked(MouseEvent e){
for(int i = 0; i<picPuzzle.length; i++){
if(picPuzzle[i] == e.getSource()){
pressT++;
if(pressT == 1) press1 = i;
if(pressT == 2) press2 = i;
}
}
if(press1 != -1&& press2 != -1){ //当两个位置都被指定时
//乱数阵列位置互换
int temp = num[press1];
num[press1] = num[press2];
num[press2] = temp;
picPuzzle[press1].setIcon(pic[num[press1]]);
picPuzzle[press2].setIcon(pic[num[press2]]);
pressT = 0;
press1 = -1;
press2 = -1;
}
//从乱数阵列的排序来看是否完成
boolean pas = true;
for(int i = 0; i<9; i++){
pas = true;
if(num[i] != i){
pas = false;
break;
}
}
if(pas){
add(success);
}
}
}
}
public class Puzzle{
public static void main(String[]args){
Cpuzzle frm = new Cpuzzle();
}
}