小球运动与线程

线程的使用方法

格式为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();
			}
			}
			}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值