All pastes #250026 Raw Edit

Something

public text v1 · immutable
#250026 ·published 2006-11-16 15:06 UTC
rendered paste body
import java.awt.*;

public class Opdracht14_06 extends Applet {
	Biljart biljart;
	Bal     bal;
	Button  knop;
	
	public void init() {
		biljart = new Biljart(0, 0, 250, 150);
		bal     = new Bal(getGraphics(), 10, 10);
		knop    = new Button("Teken bal...");
	
		knop.addActionListener(new KnopHandler());
		
		add(knop);
	}
	
	public void paint(Graphics g) {
		biljart.tekenLaken(g);
	}
	
	public class KnopHandler implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			bal.start();
		}
	}
}

class Biljart {
	private int x;
	private int y;
	private int width;
	private int height;
	private int startOfX = 50;
	private int startOfY = 50;
	
	public Biljart(int x, int y, int width, int height) {
		this.x      = x;
		this.y      = y;
		this.width  = width;
		this.height = height;
	}
	
	void tekenLaken(Graphics g) {
		g.translate(startOfX, startOfY);
		g.setColor(Color.green);
		g.fillRect(x, y, width, height);
	}
}

class Bal extends Thread {
	private int x  = 0;
	private int y  = 0;
	private int width;
	private int height;
	/* Dit is heel dirty, ik kan deze waarden beter uit de variablene uit de klasse Biljart halen.
	 * Wellicht de attributen width en height daar public en static maken, zodat ik ze kan inlezen
	 * zonder een instantie van de klasse te maken...
	 */
	private int widthOfLaken  = 250;
	private int heightOfLaken = 150;
	private int startOfX = 50;
	private int startOfY = 50;
	private Graphics g;
	
	public Bal(Graphics g, int width, int height) {
		this.g      = g;
		this.width  = width;
		this.height = height;
	}
	
	public void run() {
		g.translate(startOfX, startOfY);
		while(true) {
			teken(g, Color.red);
			slaap(10);
			teken(g, Color.blue);
			verplaats();
		}
	}
	
	public void teken(Graphics g, Color kleur) {
		g.setColor(kleur);
		g.fillOval(x, y, width, height);
	}
	
	private int dx         = 1;
	private int dy         = 2;
	private int ondergrens = 0;
	private void verplaats() {
		/* 01: Zolang y niet heightOfLaken is dan geldt: y + dy;
		 * 02: Zolang x niet widthOfLaken is dan geldt:  x + dx; 
		 * 03: Als y gelijk is aan heightOfLaken dan geldt: y - dy;
		 * 04: Als x gelijk is aan widthOfLaken dan geldt: x - dx;
		 */
		if ( y + dy > heightOfLaken || y + dy < ondergrens) {
			dy = -dy;
		}
		
		if ( x + dx > widthOfLaken || x + dy < ondergrens) {
			dx = -dx;
		}
		x += dx;
		y += dy;
	}
	
	void slaap( int millisec ) {
		try { 
			Thread.sleep(millisec);
		}
		catch( InterruptedException e) { }
	}
}