Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Animating with Swing Timer

 
Jj Hill
Ranch Hand
Posts: 41
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4467
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this isn't exactly the same thing, but it might give the answer you need.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am impressed by your mathematical abilities in that post
 
Randall Twede
Ranch Hand
Posts: 4467
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic