线程睡眠实例 Demo_月食

eg : 实训时跟着敲的实例,没什么想说的,直接奉上代码 

import javax.swing.*;
import java.awt.*;

public class EcDemo {
    public static void main(String[] args) {
        JFrame jf = new JFrame();
        jf.setSize(1024, 768);
        jf.setTitle("月食");
        jf.setVisible(true);
        MoonPanel mp = new MoonPanel();
        jf.add(mp);
        Thread tad = new Thread(mp);
        tad.start();
    }
}
class MoonPanel extends JPanel implements Runnable {
    int x = 810, y = 170;       //定义会动的月亮的坐标
    public void paint(Graphics g) {
        super.paint(g);
        this.setBackground(Color.black);
        /*画月亮*/
        g.setColor(Color.white);
        g.fillOval(860, 120, 80, 80);
        g.setColor(Color.black);
        g.fillOval(x, y, 80, 80);
        /*画星星*/
        for(int i=0;i<30;i++){
            int x = (int)(Math.random()*1024);
            int y = (int)(Math.random()*768);
            g.setColor(Color.yellow);
            g.drawString("*",x,y);
        }
    }
    public void run() {
        while (true) {
            x++;
            y--;
            if (x > 1024 && y < 0) {
                x = 810;
                y = 170;
            }
            try {
                Thread.sleep(100);//线程睡眠
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            /*每过1毫秒重新调用paint方法*/
            repaint();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值