一共俩个class
测试类 与画布类
其中线程开启需要在测试类里面
用Thread包装应用了Runnable接口的类
并且开启线程
java不允许在窗口Frame上直接画图所以需要画布Panel
生成画布对象后添加到窗口里面 add()
package huawangba;
import java.awt.*;
public class MyTestm {
public static void main(String[] args){
Frame w = new Frame();
w.setSize(1920, 1080);
w.setBackground(Color.BLACK);
MyPanel mp = new MyPanel();
Thread t= new Thread(mp);
t.start();
w.add(mp);
w.show();
}
}
画布类继承了Runnable接口 可以开启线程
package huawangba;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Panel;
public class MyPanel extends Panel implements Runnable{
int x[] =new int[300];
int y[] =new int [300];
public MyPanel(){
for(int i=0;i<300;i++){
x[i]=(int)(Math.random()*1920);
y[i]=(int)(Math.random()*1080);
}
}
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.setColor(Color.WHITE);
g.drawLine(30, 40, 50, 60);
for(int i=0;i<300;i++){
g.drawString("*", x[i], y[i]);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
repaint();
try {
for(int i =0;i<300;i++){
y[i]++;
if (y[i]>1080)
y[i]=0;
}
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Thread.sleep();存在睡死风险 需用trycatch块包围
repaint()请求向系统发出重画请求系统调用paint()应用更改画新图