This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Java in General and the fly likes Animating with Swing Timer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Animating with Swing Timer" Watch "Animating with Swing Timer" New topic

Animating with Swing Timer

Jj Hill
Ranch Hand

Joined: Jul 25, 2011
Posts: 41

I don't really know how to use javax.swing.timer in my application. My program animates a sprite moving across the screen to wherever you click, and it must look like it's traveling there. I used to use thread.sleep(), but that doesn't work anymore, so I've heard that I need to use javax.swing.timer. Here is my moveTo() method(I took the Thread.sleep() parts out):

I don't know how to insert the actionlistener. I have tried by myself but I can't seem to get it right. Btw, the moveTo method is called in a separate class, on the EDT.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
the basic scenario with a swing timer is

you draw your image (via the container's paintComponent()) at x,y
in the timer, you change x,y and call [container].repaint()
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347

this isn't exactly the same thing, but it might give the answer you need.

Visit my download page
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 43368
I am impressed by your mathematical abilities in that post
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347

lol Campbell.
i just wanted to mention that the timer can be started in the constructor. i had the run() method because i couldn't compute origin in my constructor. it seemed like a good place to start the timer.
subject: Animating with Swing Timer
It's not a secret anymore!