加深理解JAVA多线程的一个Frame绘画例子

多线程
在传统程序中,我们应该考虑在哪一瞬间应该画圆,哪一瞬间应该画矩形类似的任务等等,在多线程中,这些独立的线程,执行着各种独立的任务,绘画着不同的图形,并且在一定意义上,它们在同时运行的。

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


public class ThreadDrawJ extends JFrame{
	MovingShape [] shapes;
	public void init() {
		setLayout(null);
		setSize(426,426);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		//key step
		shapes = new MovingShape[10];
		for(int i=0;i<shapes.length;i++) {
			shapes[i]=new MovingShape(this);
			shapes[i].start();
	}
}
}

class MovingShape extends Thread{
	private int size = 100;
	private int speed = 10;
	private Color color;
	private int type;
	private int x,y,w,h,dx,dy;
	protected java.awt.Component app; //界面对象记录下来
	
	public boolean stopped;
	MovingShape(JFrame app){
		this.app = app;
		x = (int)(Math.random()*app.getSize().width);
		y = (int)(Math.random()*app.getSize().height);
		w = (int)(Math.random()*size);
		h = (int)(Math.random()*size);
		dx = (int)(Math.random()*speed);
		dy = (int)(Math.random()*speed);
		color = new Color(
				(int)(Math.random()*128+128),
				(int)(Math.random()*128+128),
				(int)(Math.random()*128+128));
		type = (int)(Math.random()*3);
	}
	// key function
		public void run() {
			while(true) {
				if(stopped)break;
				//draw();
				SwingUtilities.invokeLater(()->{
					draw();
				});
				try {Thread.sleep(130);}catch(InterruptedException e) {}
			}}
		void draw() {
			x+=dx; //移到一个新的位置继续画
			y+=dy;
			if(x<0||x+w>app.getSize().width) dx=-dx;
			if(y<0||y+h>app.getSize().height) dy=-dy;
			
			Graphics g = app.getGraphics();
			switch (type) {
			case 0:
				g.setColor(color);
				g.fillRect(x, y, w, h);
				g.setColor(Color.black);
				g.drawRect(x,y,w,h);
				break;
			case 1:
				g.setColor(color);
				g.fillOval(x, y, w, h);
				g.setColor(Color.black);
				g.drawOval(x,y,w,h);
				break;
			case 2:
				g.setColor(color);
				g.fillRoundRect(x, y,w,h, w/5, h/5);
				g.setColor(Color.black);
				g.drawRoundRect(x,y,w,h,w/5,h/5);
				break;
			}
		}

	public static void main(String[] args) {
		ThreadDrawJ f = new ThreadDrawJ();
		f.init();
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值