Hallo zusammen,
ich lasse gerade mit Hilfe von Threads ein paar Bälle in einem Fenster hin und her springen.
Die Bälle haben verschiedene Farben. Sobald ich den 4. Ball erstelle, gibt es eine bunte Schmiererei.
Wie kann ich das vermeiden?
Danke
ich lasse gerade mit Hilfe von Threads ein paar Bälle in einem Fenster hin und her springen.
Die Bälle haben verschiedene Farben. Sobald ich den 4. Ball erstelle, gibt es eine bunte Schmiererei.
Wie kann ich das vermeiden?
Danke
Java:
package Billiard;
import java.awt.*;
import javax.swing.*;
public class Tisch extends JApplet {
public void init(){
Graphics g = getGraphics();
setSize(300,400);
getContentPane().setBackground(Color.white);
Ball b1 = new Ball(40,40,3,1,50,10,g,this,Color.green);
Ball b2 = new Ball(100,100,1,-5,100,40,g,this,Color.yellow);
Ball b3 = new Ball(0,40,7,2,150,100,g,this,Color.red);
Ball b4 = new Ball(0,200,1,1,30,20,g,this,Color.black);
}
}
Java:
package Billiard;
import java.awt.*;
import javax.swing.*;
public class Ball extends Thread implements Runnable{
public int x,xalt; // X-Position
public int y,yalt; // y-Position
public int dx; // x-Alt-Position
public int dy; // y-Alt-Position
public int r; // Radius
public int speed; // Geschwindigkeit
public JApplet a; // Applet
public Color c; // Ballfarbe
public Graphics g; // Grafik
public int breite; // Applet-Fenster-Breite
public int hoehe; // y-Position
public Ball(int X, int Y, int DX, int DY, int U, int SPEED, Graphics g,JApplet applet, Color C){
x = X;
y = Y;
dx = DX;
dy = DY;
r = U/2;
speed = SPEED;
c = C;
this.g = g;
a = applet;
start(); // Starte Thread
}
public void run(){
while (Thread.currentThread() == this){
try
{ this.sleep(speed);
bewegen();
}
catch (InterruptedException e) { }
}
}
// Ball zeichnen
public void zeichnen(){
g.setColor(c);
g.fillArc(x,y,r,r,0,360);
}
// Alte Position "löschen"
public void loeschen()
{
Color f= a.getBackground();
g.setColor(f);
g.fillArc(xalt,yalt,r,r,0,360);
}
// Den Ball bewegen
public void bewegen(){
// Positionen verändern
xalt = x;
yalt = y;
x += dx;
y += dy;
// aktuelle Fenstergröße ermitteln
Rectangle rec=a.getBounds();
breite=rec.width;
hoehe=rec.height;
// Stoßt links an
if (x < 0){
dx = -dx;
}
// Stoßt oben an
if (y < 0){
dy = -dy;
}
if (x > (breite-(r))){ dx = -dx;}
if (y > (hoehe-(r))){ dy = -dy;}
loeschen();
zeichnen();
}
}