Re: Applet ball not moving
Run is called once and only once. When you start a thread it calls run to get it going. Therefore in your run statement you need to put the code in a while statement so it repeats. The while statement should check a variable that the application can set to false so as to stop the thread.
An easier approach to this sort of project is to use a Timer object rather than a separate thread.
Re: Applet ball not moving
Thanks, I didn't know that run() only runs once. But even then, the ball should have moved at least once, and it didn't, so there is something else wrong as well. And indeed, after I tried while(true){} around everything inside run(), there was still no movement.
Also, as much as I would like to use something else aside from threads (like a timer), I was told to do this with threads so I kind of have to use them.
Re: Applet ball not moving
The problem seems to be that my run() never runs, but I just don't understand why?
Re: Applet ball not moving
Probably doesn't work because you are using it wrong.
ALWAYS ALWAYS ALWAYS read the api documentation.
ALWAYS.
You can't program anything unless you read the api and know how to use the libraries.
Re: Applet ball not moving
Quote:
Originally Posted by R3N3G4D3
The problem seems to be that my run() never runs, but I just don't understand why?
run method on the Ball class doesnt get called because you instantiante the class like this Ball ball = new Ball(Xmax, Ymax);
Since it implements the runnable interface you can do somthing like this
Ball ball = new Ball(Xmax, Ymax)
Thread ballThread= new Thread(ball);
now to move the ball just invoke the start method of the ballThread
ballThread.start();
And to keep your ball moving you need a while loop inside the Ball run method to keep updating the ball's x and y coordinates
Or just try editing the Ball constructor
Code:
// just T1 to null;
Thread T1 = null;
public Ball(int a, int b)
{
Xmax = a;
Ymax = b;
x = Xmax/2;
y = Ymax/2;
P1.setPaddle(5, (Ymax/2));
P2.setPaddle((Xmax-5), (Ymax/2));
T1 = new Thread(this);
T1.start();
}
But this might not be a good idea coz.... the ball is already moving even before your applet is being started.......... I think?