黑马程序员技术交流社区

标题: 用线程做了一个倒计时,但是有问题,求解决 [打印本页]

作者: 创出一片辉煌    时间: 2012-7-27 20:44
标题: 用线程做了一个倒计时,但是有问题,求解决
用线程做了一个倒计时,但是有问题,求解决
//目标:在窗体中显示一个倒计时



import java.awt.Graphics;
import javax.swing.JFrame;

public class DaoJiShi {
        public static void main(String[] args) {
                new MyFrame("倒计时");
        }
}
class MyFrame extends JFrame implements Runnable {
        int time = 10;
        String s = "无限制";
        public MyFrame (String s) {
                super(s);
                this.setSize(200, 100);
                this.setLocation(300, 200);
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.setVisible(true);
                new Thread(this).start();
        }
        public void paint (Graphics g) {
                g.drawString(s, 50, 50);
        }
        public void run() {
                while (true) {
                        s = time + "s";
                        time--;
                        try {
                                Thread.sleep(1000);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                        this.repaint();
                        if (time == 0) {
                                System.exit(0);
                        }
                }
        }
}

作者: 刘春发    时间: 2012-7-27 20:57
        public void paint (Graphics g) {
                 g.setColor(this.getBackground());//将画笔设为背景色
             g.fillRect(0, 0, getWidth(), getHeight());//用背景色填充窗口,摸去先前画的
             g.setColor(Color.BLACK);//将画笔设为黑色,
                 g.drawString(s, 50, 50);
        }
作者: 张水荣    时间: 2012-7-27 21:26
在paint方法中加上一句代码就行了:
public void paint(Graphics g) {
                g.clearRect(0, 0, 200, 100);
                g.drawString(s, 50, 50);
        }




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2