VarunS Singh
Ranch Hand
Posts: 38
posted 10 months ago
I didn't look at your code close enough to locate a definite reason for your problem, but there are many issues which you should address:
You're not initializing your components on the EDT. Call your constructor inside a lambda passed to SwingUtilities.invokeLater(). Don't extend JFrame. Your class should use a private field that holds a reference to a JFrame. You have public members and constructors in a class that's not public. Make your classes final. Don't call Thread.sleep() on the event dispatch thread. You shouldn't call Thread.sleep() ever in the first place, but even if you do, NEVER do it on the EDT. Don't extend Thread. Either use a ExecutorService, or in this case, a SwingWorker. Don't use a for-loop with an index when an enhanced for-loop will do. Don't use raw generic types. Don't call paint() on Swing components. Call repaint() instead, and let the EDT sort the rest out. Put your fields at the start of your class, not the end.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
VarunS Singh
Ranch Hand
Posts: 38
posted 10 months ago
Don't use System.exit. In this instance nothing will happen, but it can cause serious harm in a threaded environment. Imagine you have a Thread which saves all your data in a file when you close your GUI. If you use System.exit, there is a risk of nothing being saved. Or even worse, part of it is saved and the records are corrupted. Use something like DISPOSE_ON_EXIT instead. The close button can include instructions to save any data when you close the GUI.
No, use a Timer which calls an action listener to move the balls.Stephan van Hulst wrote:. . . Don't call Thread.sleep() on the event dispatch thread. You shouldn't call Thread.sleep() ever . . .
Don't use System.exit. In this instance nothing will happen, but it can cause serious harm in a threaded environment. Imagine you have a Thread which saves all your data in a file when you close your GUI. If you use System.exit, there is a risk of nothing being saved. Or even worse, part of it is saved and the records are corrupted. Use something like DISPOSE_ON_EXIT instead. The close button can include instructions to save any data when you close the GUI.
VarunS Singh
Ranch Hand
Posts: 38
Campbell Ritchie
Sheriff
Posts: 57903
178
posted 10 months ago
That's a pleasure
. Try setting the Timer to fire more often than every 40ms and less often than every 20ms; I think you will get good movement like that. Remember that moving 10px every 20ms will take the ball right across an average‑sized display in about 1″. Consider doing that animation in JavaFX, where pixel numbers are denominated in doubles, so you can have fractional pixels. Or use doubles yourself, but you may have to cast all the doubles to ints when you paint the display.

