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

📄 ballthread.java

📁 通过继承Thread类使Ball类线程化。并把小球的弹跳动作放进Run()中执行
💻 JAVA
字号:
/*
 * Created on 2005-12-23
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package jframe;
import java.awt.*;
/**
 * @author yangbin_830
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
class Ball extends Thread{
	private Canvas box;
	private static final int XSIZE=10;
	private static final int YSIZE=10;
	private int x=0;
	private int y=0;
	private int dx=2;
	private int dy=2;
	
	public Ball(Canvas c){
		box=c;
	}
	
	public void draw(){
		Graphics g=box.getGraphics();
		g.fillOval(x,y,XSIZE,YSIZE);
		g.dispose();
	}
	
	public void move(){
		Graphics g=box.getGraphics();
		g.setXORMode(box.getBackground());
		g.fillOval(x,y,XSIZE,YSIZE);
		x+=dx;
		y+=dy;
		Dimension d=box.size();
		if(x<0){
			x=0;
			dx=-dx;
		}
		if(x+XSIZE>=d.width){
			x=d.width-XSIZE;
			dx=-dx;
		}
		if(y<0){
			y=0;
			dy=-dy;
		}
		if(y+YSIZE>=d.height){
			y=d.height-YSIZE;
			dy=-dy;
		}
		g.fillOval(x,y,XSIZE,YSIZE);
		g.dispose();
	}
	
	public void run(){
		draw();
		while(true){
			move();
			try{Thread.sleep(5);}
			catch(InterruptedException e){}
		}
	}
}

public class BallThread extends Frame{
	
	private Canvas canvas;
	public BallThread(){
		setTitle("BallThread");
		canvas=new Canvas();
		add("Center",canvas);
		Panel p=new Panel();
		p.add(new Button("Start"));
		p.add(new Button("Close"));
		add("South",p);
	}
	
	public boolean bandleEvent(Event evt){
		if(evt.id==Event.WINDOW_DESTROY)
			System.exit(0);
		return super.handleEvent(evt);
		}
	public boolean action(Event evt,Object arg){
		if(arg.equals("Start")){
			Ball b=new Ball(canvas);
			b.start();
		}
		else if(arg.equals("Close"))
			System.exit(0);
		else return super.action(evt,arg);
		return true;
	}
	public static void main(String[] args) {
		Frame f=new BallThread();
		f.resize(300,200);
		f.show();
	}
}

⌨️ 快捷键说明

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