此程式重點在thread的run執行速度太快,需要透過Thread.sleep來放慢速度,Thread.sleep需要透過try-catch來保護,處理利外狀況

補充class庫:FunInit


import java.awt.*;
import java.awt.event.*;

public class c001 extends Frame implements Runnable{
	Button[] bt = new Button[4];Button bt_power = null;
	Thread th = null;
	boolean fg=true;
	int px=0,py=0,ipx=0,ipy=0;
	
	c001(){
		Init.InitWin(this);
		Init.addWinListen(this);
		
		/*Button*/
		for(int i=0;i<4;i++){
			bt[i] = new Button("Computer["+i+"]");
			Init.setButton(bt[i], 80, 40, 100, 100+i*50);
			this.add(bt[i]);
		}
		bt[3].setLabel("ME");
		
		bt_power = new Button("Press");
		Init.setButton(bt_power, 80, 40, 200, 400);
		this.add(bt_power);
		bt_power.addActionListener(
			new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					ipx = bt[3].getX()+50;ipy = bt[3].getY();
					bt[3].setLocation(ipx,ipy);
				}	
			}
		);
		
		Thread th = new Thread(this);
		th.start();
		
	}
	
	public static void main(String[] args){
		c001 mm = new c001();
	}

	@Override
	public void run() {
		while(fg){
			for(int i=0;i<3;i++){
			px = bt[i].getX()+fun.Rand(5);py = bt[i].getY();
			bt[i].setLocation(px,py);
			if(px>820||ipx>820){fg=false;break;}
			}
			
			try{Thread.sleep(10);}catch(Exception e){}
		}
	}
	
	public void paint(Graphics g){
		g.drawLine(900, 100, 900, 600);
	}
}
arrow
arrow
    創作者介紹
    創作者 Kuihao 的頭像
    Kuihao

    溫暖午後的金針田__孕育有趣的創新

    Kuihao 發表在 痞客邦 留言(0) 人氣()