一、逻辑部分
public class GridCalculator {
private int row = 0;
private int column = 0;
private int nextScore = 0;
private long startTime = 0;
private int costTime = 0;
private boolean isTrainning = false;
private boolean isFinished = false;
private Timer timer;
GridCalculator(int rows, int columns) {
this.row = rows;
this.column = columns;
}
public List<Integer> generateSequence() {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= row * column; i++) {
list.add(i);
}
Collections.shuffle(list);
return list;
}
public void startTrain() {
this.costTime = 0;
this.startTime = new Date().getTime();
this.isTrainning = true;
this.isFinished = false;
this.nextScore = 1;
this.timer = new Timer();
this.timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
costTime = (int) ((new Date().getTime() - startTime) / 1000);
}
}, 0, 500);
}
public void stopTrain() {
this.isTrainning = false;
//this.costTime = (int) ((new Date().getTime() - this.startTime) / 1000);
this.timer.cancel();
}
public boolean trySocre(int next) {
boolean success = false;
if (isTrainning && next == this.nextScore) {
if (next == this.row * this.column) {
// finish
//this.costTime = (int) ((new Date().getTime() - this.startTime) / 1000);
this.isFinished = true;
this.isTrainning = false;
this.timer.cancel();
}
this.nextScore++;
success = true;
}
return success;
}
public boolean isFinishTrain() {
return this.isFinished;
}
public int getCostTime() {
if (isFinished || isTrainning) {
return this.costTime;
} else {
//return Integer.MAX_VALUE;
return 0;
}
}
}
二、页面部分
public class GridPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<JButton, Integer> gridButtonMap;
private List<Integer> list;
private GridCalculator calculator;
private JButton btStart;
private JButton btStop;
private JLabel lbInfo;
private JLabel lbUsedTime;
private List<JButton> btList;
private Timer trainTimer;
private Color defaultColor;
private void initGridButton(List<JButton> btList) {
this.calculator = new GridCalculator((int) Math.sqrt(btList.size()),
(int) Math.sqrt(btList.size()));
this.list =