do the task repeated time steps to create swing timer: create the actionlistener create the timer constructor then pass time and actionlistener in that implement the actionPerformed() function in which do your task use timer.start() for start the task between the time specified in timer constructor, use timer.stop() for stop the task Example:
This class should prefer to be 500 * 500 pixels in size. Its constructor should first fill an ArrayList field with 100 Particle objects, then start a Swing Timer that ticks 25 times a second. At each tick, the action listener should first call the method move for each particle, and then call repaint.
A quote from the link specified by trashgod says In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, pre-existing timer thread and the GUI-related task automatically executes on the event-dispatch thread.
Don't call timer.start(); and/or timer.stop() in the paintComponent method, this makes no sense what so ever, painting may occur for any number of reasons, my of which you have no control over. Don't call Thread.sleep in your paintComponent, that's the point of have the Timer. You're just preventing Swing from updating the screen or process any new events Timer acts as a psudo loop, on each ...
1) Declare the Timer as an attribute of the class. 2) Set it up ready to go in the constructor. 3) As action listener for the start button (suggest check box or radio button), start it. 4) On action to stop it, .. stop it. General tip: For better help sooner, edit to add a minimal reproducible example or Short, Self Contained, Correct Example. It should take no more than 30-40 lines of code to ...
new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { // your code here } }, 5000 ); EDIT: javadoc says: After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to ...
As mentioned you can use and reuse a single timer (and its associated thread) for scheduling multiple timed tasks instead of creating a new one every time. Check out the javadoc for Timer.