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

📄 partialpaintdemo.java

📁 java手机程序开发随书光盘源代码
💻 JAVA
字号:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.*;

public class PartialPaintDemo extends MIDlet{

	Display display;
	MyCanvas myCanvas;

	public PartialPaintDemo(){
		display = Display.getDisplay(this);
		myCanvas = new MyCanvas();
	}

	public void startApp(){
		display.setCurrent(myCanvas);
		myCanvas.start();
	}

	public void pauseApp(){
	}

	public void destroyApp(boolean unconditional){
	}

}

class MyCanvas extends Canvas implements CommandListener{

	Ball[] balls = new Ball[2];
	Command fastCmd, slowCmd;

	public MyCanvas(){

		fastCmd = new Command("加快", Command.SCREEN, 1);
		slowCmd = new Command("变慢", Command.SCREEN, 2);
		for(int i=0;i<balls.length;i++){
			int color = 0xFFFF/balls.length;
			balls[i] = new Ball(this, i*50, color*i);
		}
		addCommand(fastCmd);
		addCommand(slowCmd);
		setCommandListener(this);
	}

	public void start(){

		for(int i=0; i<balls.length; i++){
			balls[i].start();
		}
	}

	public void paint(Graphics g) {

		g.setColor(0xffffff);
		g.fillRect(0, 0, getWidth(), getHeight());

		for(int i = 0; i<balls.length; i++){
        	balls[i].paint(g);
		}
	}

	public void commandAction(Command c, Displayable d){

		if(c == fastCmd){
			Ball.delay -= 50;
		}
		else if(c == slowCmd){
			Ball.delay += 50;
		}
	}

}

class Ball implements Runnable{

	final static int UP = 1;
	final static int DOWN = 2;
	private MyCanvas myCanvas;
	private Thread t;
	private int diameter;
	private int posX, posY;
	private int direction;
	static int delay;
	int color;
	Random random;

	public Ball(MyCanvas myCanvas, int posX, int color){
		this.myCanvas = myCanvas;
		random = new Random();
		t = new Thread(this);
		this.posX = posX;
		posY = myCanvas.getHeight()-diameter;
		diameter = 40;
		direction = UP;
		delay = 200;
		this.color = color;
	}

	 void paint(Graphics g) {
		g.setColor(color);
		g.fillArc(posX, posY, diameter, diameter, 0, 360);
    }

    public void start(){
    	t.start();
    }

	public void run() {

		while (true) {
			if(direction == UP){
				posY -= 2;
			}
			else if(direction == DOWN){
				posY += 2;
			}
			if(posY < 0){
				posY = 0;
				direction = DOWN;
			}
			if(posY > myCanvas.getHeight()-diameter){
				posY = myCanvas.getHeight()-diameter;
				direction = UP;
			}
			if(direction == UP){
				//myCanvas.repaint();
				myCanvas.repaint(posX, posY, diameter, diameter + 4);
			}
			else if(direction == DOWN){
				//myCanvas.repaint();
				myCanvas.repaint(posX, posY - 4, diameter, diameter+4);
			}
			//myCanvas.repaint();

			try {
				Thread.sleep(delay);
			} catch (Exception ex) {}
		}
	}

}

⌨️ 快捷键说明

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