多线程练习2

import java.awt.*;
import java.awt.event.*;
public class window extends Frame//建立主类
{
 private Image iBuffer;
 private Graphics gBuffer;
 int x=290,y=0;
 public paintThread pT;
 public window()//构造函数
 {
  pT=new paintThread(this);//开辟线程
  this.setTitle("move");
  this.setBounds(50,50,300,300);
  this.addWindowListener(new closeWin());
     this.setVisible(true);
  pT.start();//开启线程
 }
  public void paint(Graphics g)//绘图方法
    {
         if(iBuffer==null)
        {
    iBuffer=createImage(this.getSize().width,this.getSize().height);
    gBuffer=iBuffer.getGraphics();
  }
  gBuffer.setColor(getBackground());
        gBuffer.fillRect(0,0,this.getSize().width,this.getSize().height);
        gBuffer.setColor(Color.RED);
  gBuffer.fillOval(x,y,10,10);//绘制圆
        g.drawImage(iBuffer,0,0,this);
 }
 public void update(Graphics g)//重载绘图函数
 {
  paint(g);
 }
 
 public static void main(String[] args)//主算法
 {
  window a = new window();
 }
}
class paintThread extends Thread//绘图线程类
{
    window a;
       public paintThread( window a) //构造函数
       {
           this.a=a;
       }
       public void run()//重载run()函数
       {
           while(true)//线程中的无限循环
           {
               try
      {
                  sleep(30); //线程休眠30ms
                }
    catch(InterruptedException e){}
              a.y+=1; //修改小圆左上角的纵坐标
              a.x-= 1;
              if(a.y>300) //小圆离开窗口后重设左上角的纵坐标
              {
               a.y=0;
               a.x=290;
              }
              a.repaint();//窗口重绘
           }
       }
}
class closeWin extends WindowAdapter//关闭窗口
{
      public void windowClosing(WindowEvent e)
 {
    Frame frm =(Frame)(e.getSource());
    frm.dispose();
    System.exit(0);
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值