高手帮忙给我的扫雷游戏JAVA代码添加一个计时功能。

package default2;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/*主类*/

public class Main{
public static void main(String args[]){
(new MainBomb()).show();
}
}

class Bomb extends JButton{

public int num_x,num_y; //第几号方块
public int BombRoundCount; //周围雷数
public boolean isBomb; //是否为雷
public boolean isClicked; //是否被点击
public int BombFlag; //探雷标记
public boolean isRight; //是否点击右键

public Bomb(int x,int y) {
BombFlag = 0;
num_x = x;
num_y = y;
BombRoundCount = 0;
isBomb = false;
isClicked = false;
isRight = false;
}
}
/*窗口及算法实现类*/

class MainBomb extends JFrame implements ActionListener,MouseListener{

public JTextField text;
public Label nowBomb,setBomb;
public int BlockNum,BombNum; //当前方块数当前雷数
public Icon icon_bomb = new ImageIcon("Bomb.gif"); //踩雷
public Icon icon_bomb_big = new ImageIcon("bomb_big.gif"); //踩雷标记
public Icon icon_flag = new ImageIcon("flag.gif"); //雷标记
public Icon icon_question = new ImageIcon("question.gif"); //疑惑是否有雷
public JButton start = new JButton(" 开始 ");
public Panel MenuPamel = new Panel();
public Panel mainPanel = new Panel();
public Bomb[][] bombButton;

/*界面设计*/
public MainBomb() {
super(" JAVA课程设计扫雷游戏 ");
BlockNum = 64;
BombNum = 10;
Container c=getContentPane();
c.setBackground(Color.lightGray);
c.setLayout(new BorderLayout());
text=new JTextField("10 ",3);
nowBomb = new Label("当前雷数"+" "+BombNum+"");
setBomb= new Label("设置地雷数");
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
BombNum = Integer.parseInt(text.getText().trim());
if(BombNum >= 10 && BombNum < 50 )
replay();

public int time=1000* 60; //60秒倒计时
public boolean running=true;//是否一直运行
JLabel label=new JLable();//显示时间的标签

//启动计时
public void startTimer(){
new java.lang.Thread(new Runnable(){
public void run(){
while(running){
try{
Thread.sleep(1000);//睡一秒
}catch(Exception e){}
time--;
lable.setText(String.valueof(time));
this.update();// 把你的界面刷新一下
if(time<0){//倒计时到零,满足条件
//your code: 游戏失败,做点处理
running=false;//记得置成false否则不退出
}
}
}
}).start();
}

使用时,在你需要使用的时候 调用 startTimer()方法即可
你可以看到, startTimer方法里的线程在不断地改变time的值,每秒减一
所以你需要在你的GUI界面上安装一个 JLabel label,不断地改变label的内容为time就行了
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-01-08
Timer,quartz
第2个回答  2009-01-08
Timer
相似回答