gpt4 book ai didi

java - GUI计时器不停止

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:50 26 4
gpt4 key购买 nike

我的 GUI 计时器有问题。当玩家点击雷区中的按钮时,我启动计时器,并在游戏结束时停止计时器。

我第一次测试游戏时,计时器正常启动和结束。但是,如果我尝试玩第二轮游戏,我的计时器不会停止。

public class Minesweeper7 extends JFrame implements ActionListener {

static public boolean revealed [][];

public static CountTimer ct;

public Minesweeper7 (int row, int column) {

ct = new CountTimer ();

}

private void setTimerText (String sTime) {

timeLabel.setText (sTime);

}

public void actionPerformed(ActionEvent event){

String coords = event.getActionCommand();
String[] squarePressed = coords.split(",");

x_pressed = Integer.parseInt(squarePressed[0]);
y_pressed = Integer.parseInt(squarePressed[1]);

System.out.println("The button you have pressed is " + x_pressed + ", " + y_pressed);

if (ct.timer.isRunning() == false){
ct.start ();
System.out.println ("timer is running");
}

reveal (row,column,x_pressed,y_pressed,revealed,mines,revealed_number);

gameEnd (row, column, revealed, mines, countMines, counter, end);

System.out.println("There are " + countMines + " .");

System.out.println("");

for (int r = 0;r<row;r++){
for (int c = 0;c<column;c++){

label[r][c].setText(String.valueOf(revealed_number[r][c]));

}
}

}

public void reveal () {
//a recursive method that reveals my buttons
}

public static void main (String args []) {

java.awt.EventQueue.invokeLater (new Runnable () {
public void run () {
new Minesweeper7 (10, 10);
}
});

}

public void gameEnd (int row, int column, boolean revealed [][], boolean mines [][], int countMines, int counter, boolean end) {

for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
if (mines [r][c] == false && revealed [r][c] == true) {
counter++;
}

else if (mines [r][c] == true && revealed [r][c] == true) {
System.out.println ("Sorry, you lost because you clicked on a mine.");
end = true;
break;
}
}
}

if (counter == (row*column-countMines)) {
System.out.println ("Congratulations! You won the game!");
end = true;
instruction.setText("Congratulations! You won the game!");
}

if (end == true) {
ct.stop ();
}

}

public class CountTimer implements ActionListener {
public static final int ONE_SECOND = 1000;
public int count = 0;
public boolean isTimerActive = false;
public Timer timer = new Timer (ONE_SECOND, this);

public CountTimer () {
count = 0;
setTimerText (TimeFormat (count));
}

public void actionPerformed (ActionEvent e) {
if (isTimerActive) {
count++;
setTimerText (TimeFormat (count));
}
}

public void start () {
count = 0;
isTimerActive = true;
timer.start ();
}

public void stop () {
timer.stop ();
}

public void reset () {
count = 0;
isTimerActive = true;
timer.restart ();
}
}

}

最佳答案

如果你开始一个新游戏,你可以创建一个新的计时器,而不是开始和停止。

if (game end) {

timer = new Timer();
timer.start();
}

关于java - GUI计时器不停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com