⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threaddraw.java

📁 J2ME开发实例代码! 内含有可执行的代码!
💻 JAVA
字号:
//ThreadDraw.java
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class ThreadDraw extends MIDlet
{
	
	public void startApp()
	{
		Display	display = Display.getDisplay(this);
		display.setCurrent( new ThreadDrawCanvas() );
	}
	
	public void pauseApp()
	{
	}
	public void destroyApp(boolean unconditional)
	{
	}
}

class ThreadDrawCanvas extends Canvas
{
	int width, height;
	Graphics g;
	MovingShape [] shapes;
	ThreadDrawCanvas()
	{
		width = getWidth();
		height = getHeight();
		shapes = new MovingShape[ 5 ];
		for( int i=0; i<shapes.length; i++ )
			shapes[i] = new MovingShape(this);

	}
	public void paint( Graphics g )
	{
		this.g = g;
	}

}

class MovingShape extends Thread
{
	
	boolean bContinue = false;
	private int size=50;
	private int speed=10;
	private int color;
	private int type;
	private int x,y,w,h,dx,dy;
	protected ThreadDrawCanvas app;
	Random rnd = new Random();

	
	MovingShape( ThreadDrawCanvas app )
	{
		this.app = app;
		x = random(app.width);
		y = random(app.height);
		w = random(size );
		h = random(size );
		dx = random(speed );
		dy = random(speed );
		color =  
			((random(128)+128)<<16)  | 
			((random(128)+128)<<8)	|
			((random(128)+128));
		type = random( 3 );
		bContinue = true;
		this.start();  // 注意,线程刚构造出来,这里就立即进行启动
	}
	
	public void run()
	{
		while( true ){
			x += dx;
			y += dy;
			if( x<0 || x+w>app.width ) dx = -dx;
			if( y<0 || y+h>app.height) dy = -dy;
			Graphics g = app.g;
			
			if( g!= null ) switch( type ){
		   
				case 0:
					g.setColor(color);
					g.fillRect( x,y,w,h ); 
					g.setColor( 0 );
					g.drawRect( x,y,w,h );
					break;
				case 1: 
					g.setColor(color);
					g.fillArc( x,y,w,h,0,360 ); 
					g.setColor( 0 );
					g.drawArc( x,y,w,h,0,360 );
					break;
				case 2: 
					g.setColor(color);
					g.fillRoundRect( x,y,w,h,w/5,h/5); 
					g.setColor( 0 );
					g.drawRoundRect( x,y,w,h,w/5,h/5 );
					break;
			}
			//System.out.println(x+","+y+","+w+","+h+":"+type+","+dx+","+dy);
			try{ Thread.sleep(130); } catch( InterruptedException e ){}
			app.repaint();
		}
	}
	
	int random( int nMax )
	{
		long r = (long)(rnd.nextInt());
		if(r<0) r = -r;
		r = (r*nMax)/(1L<<31);
		//System.out.println( r +"/" +nMax );
		return (int) r;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -