Links und Funktionen
Sprachumschaltung

Navigationspfad


Inhaltsbereich

Musterlösung Aufgabe 3-2

Java source code icon Loesung.java — Java source code, 1 KB (1746 bytes)

Dateiinhalt

import java.awt.Graphics;
import java.awt.Point;

public class Loesung {

	public static void main(String[] args) {

		// Größe des Fenster:
		final int xsize = 500, ysize = 500;
		// Mittelpunkte der Kreise:
		final int x1 = 225, y1 = 250;
		final int x2 = 275, y2 = 250;
		// Radien der großen und kleinen Kreise
		final int radiusL = 20;
		final int radiusS = 8;
		final int maxDist = 10;

		CanvasFrame frame = new CanvasFrame("Aufgabe 3-2", xsize, ysize);

		Graphics canvas = frame.getGraphics();
		canvas.clearRect(0, 0, xsize, ysize);
		canvas.drawOval(x1 - radiusL, y1 - radiusL, 2 * radiusL, 2 * radiusL);
		canvas.drawOval(x2 - radiusL, y2 - radiusL, 2 * radiusL, 2 * radiusL);
		canvas.fillOval(x1 - radiusS, y1 - radiusS, 2 * radiusS, 2 * radiusS);
		canvas.fillOval(x2 - radiusS, y2 - radiusS, 2 * radiusS, 2 * radiusS);
		frame.repaint();
		while (true) {

			Point mousePosition = frame.waitMouseMoved();
			canvas.clearRect(0, 0, xsize, ysize);

			double dx = mousePosition.x - x1;
			double dy = mousePosition.y - y1;
			double dist = Math.sqrt(dx * dx + dy * dy);
			canvas.drawOval(x1 - radiusL, y1 - radiusL, 2 * radiusL, 2 * radiusL);
			int x = x1 + (int) (dx / dist * Math.min(maxDist, dist));
			int y = y1 + (int) (dy / dist * Math.min(maxDist, dist));
			canvas.fillOval(x - radiusS, y - radiusS, 2 * radiusS, 2 * radiusS);

			dx = mousePosition.x - x2;
			dy = mousePosition.y - y2;
			dist = Math.sqrt(dx * dx + dy * dy);
			canvas.drawOval(x2 - radiusL, y2 - radiusL, 2 * radiusL, 2 * radiusL);
			x = x2 + (int) (dx / dist * Math.min(maxDist, dist));
			y = y2 + (int) (dy / dist * Math.min(maxDist, dist));
			canvas.fillOval(x - radiusS, y - radiusS, 2 * radiusS, 2 * radiusS);

			frame.repaint();
		}
	}
}

Artikelaktionen


Funktionsleiste