线程的使用方法
格式为public void 参数名 extends Thread{}
在Thread 这个类中有一个run 方法
即只要在主程序中写下 **调用的该类的参数名.start ()**即可
如下所示
主程序
public class zhuye implements MouseListener {
Threadsleep thread = new Threadsleep();
public void initUI() {
JFrame lgjf = new JFrame();
lgjf.setSize(900, 900);
lgjf.setLocationRelativeTo(null);
lgjf.getContentPane().setBackground(Color.white);
lgjf.setLayout(new FlowLayout());
lgjf.setDefaultCloseOperation(3);
lgjf.setVisible(true);
Graphics g = lgjf.getGraphics();
thread.g = g;
listen.g=thread.h;
thread.start();
}
public static void main(String[] args) {
new zhuye().initUI();
}
}
线程中
public class Threadsleep extends Thread {
public void run() {
}
}
小球运动
需要解决的问题
1,如何在一个线程中运行多个小球
2,如何使小球不断运动
让小球不断运动只需建立死循环即可
而要在一个线程中运行多个小球则需要创建一个数组,让每一次循环时遍历一次该数组。
动态数组的使用方法为
定义:ArrayList<类名> 参数名=new ArrayList<类名>();
调用:参数名.get(用数字指代的位置);
添加:参数名.add(同类的参数名; 添加到数组末尾
动态数组相比于其他数组特殊在于他能添加内含物,不需要定义数组的长度,如果不考虑添加小球,用该类定义一个普通的数组一样可以实现多个小球运动。
因此线程中如下
public class Threadsleep extends Thread {
ArrayList<Ball> list = new ArrayList<Ball>();
BufferedImage sd = new BufferedImage(900, 900, BufferedImage.TYPE_INT_ARGB);
Graphics h = sd.getGraphics();
int x, y;
Graphics g;
private double t;
private int radius = 50;
int j = 0;
int n = 1;
int l = 0;// 用于判断碰撞是否已经进行过了
public void run() {
h.setColor(Color.red);
h.fillOval(100, 100, radius, radius);
while (true) {
for (int i = 0; i < list.size(); i++) {
Ball ball = list.get(i);
ball.move(n, radius, h, chase);
/*ball类的move方法中写的是
g.setColor(Color.white);
g.fillOval(x,y,radius,radius);
g.setColor(Color.black);
g.fillOval(x,y,radius,radius);*/
}
g.drawImage(sd, 0, 0, null);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}