Here is a simple piece of code that I have written to move a ball diagonally across the screen using a thread :
I want to extend the idea to multiple threads i.e., multiple balls moving across the screen with their starting points generated randomly. However, I am lost as to how to go about doing the same. For instance, what should the condition be in the while loop in the run method ?
Unless the balls do more complicated things, I think representing each with its own thread is overkill. I'd suggest to create a Ball class that holds all required information about one ball (x and y coordinates, speed, direction, color, etc.), and then to have an array of those that the main thread iterates through and manipulates.
Because you're only drawing one oval each time. But I see quite a few other problems in this code:
- calling repaint on a thread other than the EDT.
- forgetting the call to super.paint(g) at the start of the paint method.
- trying to stop by nulling out the variables; the threads will still continue though.
I suggest you check out javax.swing.Timer. This will trigger events regularly on the EDT itself. If this interval is small enough users will see a fluent movement.