Timed 2d animation with AWT

I am making an AWT app that involves moving a series of images across the screen at a set interval.
There is a ton of code involved with this, so I am going to try to keep this as abstract as possible.
In short, the images need to traverse an 800 pixel space (horizontally) in 3715.192.... milliseconds, or 3715192743.764... nanoseconds, which is 4343990.929... nanoseconds per pixel.
Each of the images has a Point object that tracks it's current position.
The panel the objects are drawn on has a inner class that implements runnable() called Animator. The Animator waits every 4343990 ns, and iterates each object's Point.x by -1 (right to left), like this:
class Animator implements Runnable {
     WordPanel wordPanel;
     Animator(WordPanel wordPanel) {
          this.wordPanel = wordPanel;
     public void run() {
          // TODO Auto-generated method stub
          while (true){
               while (TransportState.getCurrentState()!=TransportState.TransportEventStates.STOP) {
                    long startTime = System.nanoTime();
                                // the next while loop should throttle execution of the loop to 4343990 ns
                    while ((System.nanoTime() - startTime) <= 4343990L) {
                         Thread.yield();
                    if (songFileWordImages != null && songFileWordImages.size()>0) {
                         synchronized (songFileWordImages) {
                              for (SongFileWordImage sfwi : songFileWordImages) {
                                   synchronized (sfwi) {
                                        int oldX = sfwi.getPoint().x;
                                        int oldY = sfwi.getPoint().y;
                                        sfwi.setPoint(new Point(oldX - 1, oldY));
                    wordPanel.repaint();
}Everything is back-buffered (double buffered) properly, the problem isn't flickering. The problem is with the while loop that is supposed to throttle the iteration of the x values to move the images. It seems to be waiting too long between iterations.
I arbitrarily lowered the 4343990L by half, and that made it closer to the right speed, but still too slow. From that point, I just continually arbitrarily lowered the value until it "looked right".
The problem is that I can't stand the arbitrary solution, I need to know WHY.
Testing said loop, I had it output System.nanoTime() - startTime to the screen, and found that it sometimes seemed to go "back in time". In theory, the values should have continually gotten bigger until they hit 4343990, but I noticed that it only did it generally, and that there were some non-linear values in the output. WTF?
Can someone give me some pointers on doing smooth animation in AWT without having to deal with ns? I know that Swing has some animation tools, but I want this to be 100% AWT.

Here is an example of using the Swing timer class, to show how simple it is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTimerTest extends JFrame implements ActionListener {
     private Timer timer;
     private JLabel label;
     private int iterCount;
     public SwingTimerTest() {
          int ms = 50; // Delay at which to repaint, in milliseconds.
          JPanel cp = new JPanel(new BorderLayout());
          cp.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
          JLabel topLabel = new JLabel("I will get updated every " + ms +
                                                  " milliseconds.");
          cp.add(topLabel, BorderLayout.NORTH);
          label = new JLabel("I have been updated 0 times.");
          cp.add(label, BorderLayout.SOUTH);
          iterCount = 0;
          timer = new Timer(ms, this);
          timer.setRepeats(true);
          timer.start();
          setContentPane(cp);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          setTitle("Swing Timer Demo");
          pack();
     // Called by our Timer at a fixed delay.
     public void actionPerformed(ActionEvent e) {
          if (e.getSource()==timer) {
               iterCount++;
               label.setText("I have been updated " + iterCount + " times.");
     public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    new SwingTimerTest().setVisible(true);
}

Similar Messages

  • How to synchronize animation with time?

    I want to synchronize animation with time, but I can't determine the current time, because the return value of the System.currentTimeMillis() method is updated only every 10 milliseconds.
    The following example demonstrates it:
    import java.applet.Applet;
    import java.awt.Graphics;
    class TimeStep extends Applet
      long minimalStep=1000L;
      long lastTime=System.currentTimeMillis();
      public void paint(Graphics g)
        g.drawString("Minimal timestep: "+minimalStep,5,30);
        for (int i=25;i-->0;)
          while (true)
             long newTime=System.currentTimeMillis();
             long step=newTime-lastTime;
             if (step>0L)
                 if (step<minimalStep)
                    minimalStep=step;
                 lastTime=newTime;
                 break;
        repaint();
    }It causes flickers by most framerates:
    import java.applet.Applet;
    import java.awt.Graphics;
    class SynchronizedAnimation extends Applet
      static final int FRAME_RATE=90;     // 100 works, 90 flickers
      static final int STEP=5;
      static final int WIDTH=640;
      static final int HEIGHT=20;
      static final long FRAME_TIME=1000L/FRAME_RATE;
      int lastPosition,newPosition;
      long lastTime=System.currentTimeMillis();
      public void paint(Graphics g)
        long waitedTime=lastTime+FRAME_TIME;
        while (waitedTime-System.currentTimeMillis()>0L);
        lastTime=waitedTime;
        newPosition=(lastPosition+STEP)%WIDTH;
        g.drawLine(newPosition,0,newPosition,HEIGHT);
        if (lastPosition!=newPosition)
            g.setColor(getBackground());
            g.drawLine(lastPosition,0,lastPosition,HEIGHT);
            lastPosition=newPosition;
        repaint(0L);
      public void update(Graphics g)
        paint(g);

    On windows 9x its even worse. The timer is only updated every 50/60 milliseconds.
    Instead you could do something like keep the time when the animation starts, and then everytime you want to paint, check how much time has gone since then and calculate where the animation has gone to at this point.
    Even if you can only update every 50 ms, it gives you 20 frames. I don't think its that bad.

  • Sprite animation with double buffering

    Hello, I am writing a game. I am not using swing. Just awt.
    I have several books I am looking at right now. One uses the
    BufferedImage class to create a buffered sprite. The other book instead uses the Image class to impliment double buffering. So, I am really confused now. I do not know if I should use the BufferedImage class or the Image class. Note that
    Please help. Which method is the best to use?
    Val

    These links may assist you in full-screen animation with double-buffering:
    http://www.sys-con.com/java/article.cfm?id=1893
    http://www.meatfighter.com/meat.pdf
    - Mike

  • Creating animations with transparent backgrounds?

    I'm running into some problems when using After Effects to create animations with transparent backgrounds for Keynote...
    I use animated gifs and short quicktime movies with uniform backgrounds as source files, use color keying to take out the backgrounds, preview them to see if they look OK, render the results as RGB+alpha, and... they don't show up as transparent in Keynote. They work in Powerpoint, however. I've tried outputting as .mov, as .gif, as premultiplied vs straight alpha... no joy. Can someone explain (or point me to an explanation) of how Keynote differs from other programs in its handling of transparency? What am I missing?

    Using a TYPE_INT_ARGB BufferedImage worked beautifully. I had played around with Image for hours, but it never occurred to me that BufferedImage would be needed. :)
    many, many thanks,
    Steven

  • I'm a Graphic Designer and Animator with a Mid 2012 15" MBP...Programs slowing need up grade

    Hey everyoe,
    I'm a Graphic Designer and Animator with a Mid 2012 15" MBP. My programs get REALLY SLOW, ToonBoom Harmony and Sometimes Illustrator, HELP! I upgraded my Ram to 16GB LONG time ago and it's made a big difference but still the stuff I make is semi complicated/detailed I can't imagine this is the strength of my MBP I refuse to accept that. WIth that said HELP ME PLZ!!! I have deadlines and I dont know what else to do! Steve Jobs my life is your hands right now man...

    Maz0327,
    if you boot into Safe mode, log in, and run your graphic design and animation apps, do they run just as slowly then?

  • How do i create an animation with one frame for each layer?

    I have 76 sequential images that i've loaded as layers using bridge, then aligned using photoshop.
    I would now like to create a 76 frame animation with one animation frame for each layer
    (the layers are in sequential order).
    is there an easy way to do this
    or do i have to create 76 frames (can duplicate multiple to speed it up)
    then set layer visibility for each frame?
    thanks
    bill w
    astro.whwiii.net

    thanks for all the replies
    got it
    here's a rough draft of 2 hours of sunshine
    http://whwastro.homestead.com/files/big/31-05-2014-prom-animation.gif
    -bill w
    astro.whwiii.net

  • Timed out error with Fp-2000 while find devices

    When I try to Find Devices in MAX (version 3.1) I get the error "The connection to a remote device timed out". With the File Transfer and the Install Software I don't have the problem. I tried to use a different Workstation, different IP Address but the problem persists. Do you have a solution?
    Vincenzo Pascariello

    Hi,
    the 2 flashes of the Status led are indicating that the software is not properly installed.
    As for the Devices not found problem, I don't think the problem has to do with MAX, FP software or LabVIEW 7.1.
    When devices are not found, generally there is a communication problem.
    This can be possibly due to 2 situations:
    1) There is a bent Pin on one of the FP-TB which is making the Fieldpoint bus not to work properly.
    2) There are network problems. One way to workaround this might be to connect to the FP-2000 using a crossover cable and link directly to the PC. This avoids any network connection problems.
    The last thing you need to take into account is that the FP-2000 module might be damaged and need repair.
    If you are unable to get to a solution, contact NI Tech Support at
    02.41.30.92.17 and ask for support with an Engineer
    Regards,
    AlessioD
    National Instruments

  • Troubles importing Flash 10 Animation with 3D Transform

    I am looking for any workaround/experiences for importing a Flash 10 animation with 3D transforms. Currently, doing this will wig out Captivate 4 and break the embedded animation in all sorts of ways. AS3 support in Captivate is turned on and the same animation will load and play correctly if the 3D transform is removed. All other Flash 10/AS3 possibilites work including motiosn graphs and filters.
    I find the 3D transform option of Flash CS4 to be one of the most powerful features ever introduced in Flash and would allow some incredible breakthrough design possibilities for my Captivate projects, if it would just support it! Any experiences with this issue welcomed. A bug report has been submitted also, but looking for a quicker remedy.

    Problem Resolved!
    I got this tip from Vikram (Adobe Support)
    1. Open your project having Flash Player 10 animations involving 3D transforms.
    2. Click the Edit menu and select Preferences.
    3. Select "Publish settings" under the "Project" section.
    4. Check "Animations" option under the "Externalize resources" section.
    5. Press OK.
    6. Now click the publish button.
    7. In the publish dialog, select Flash Player 10 from the "Flash Player version:" drop down.
    8. Click publish.
    (F4 preview may not work, so use preview in browser)
    Also, you may need to be wary of embedded scripted symbols as they may loose reference to the parent symbol after being embedded in yoru your CP4 project containing 3D transforms. My advice here is to try to script using as much object oriented js as possible in the main timeframe.
    I am using a combination of localConnect and ExternalInterface functions to control the 3D animation from captivate quiz buttons. This process adds a whole new level of interactivity and visual interest to your captivates!

  • JMenu with AWT component

    dear friends;
    i have added menu bar in Jframe which is containes menues.
    AWT component is added the the same frame .
    problem is:
    menues are overlapping with awt component while i clicked the menu bar.
    dear friends help me immediately.
    thank u

    dear friends help me immediately.It's your own fault or combining Swing and AWT widgets. You're not supposed to do that, as it can lead to strange effects. Like this one.

  • Java Applets with AWT

    Hi,
    I have the problem to display the applet with AWT. If I am running the same applet in the internal server it works fine.If I am running through the web its giving Class not found exception.That web server also is mapped into the same server.
    Here is the code.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class NotHelloWorldApplet extends Applet
    public void init()
         try{
              setLayout(null);
              Label label1= new Label("Hello World!");
              label1.setSize(200,200);
              add(label1);
         }catch(Exception e){System.out.println(e);}
    <html><body>
    <applet
    code="NotHelloWorldApplet"
    codebase="."
    width=600 height=400
    >
    </applet>
    </body></html>
    can anyone help me please.
    Thanks

    Hello,
    Even I executed the program. Its works fine. I guess you must be having problem with the codebase. Just change the address in the codebase from current directory to the address where the class file is there and also change the permissions(set attributes to 755) of the class file. Hope this helps you.
    Regards,
    Sarada.

  • How to control animation with touch

    Hello! I need some help with controlling animations with touch. I am building a fake app and need to 'unlock' an iphone (slide an arrow along a track and then have it fade into another page). I have been using http://forums.adobe.com/message/4865693 that thread. The prototype link listed there is similar to waht I need to recreate, but I think I need an 'on touch' actino instead of a mousemove one.
    http://assets.ordienetworks.com.s3.amazonaws.com/the_occasional/checkerPro/checkerPro.html
    That is a link to the Edge file I have been working on, using the info in the thread above. It is broken at the moment, and I am terrible with javascript and have no idea how to move forward. I have figured that I'll need an 'on touch' action instead of the mouseover one, but I'm not sure how to build it.
    If there is a working example of this on a different thread that I've missed I'd love a link as well!!
    Thank you!!

    Hi, akall-
    There are a number of touch events that you can use to accomplish what you want.  You can try using the touchmove event instead of the mousemove event, and stick your code in there.
    Hope that helps,
    -Elaine

  • Flash animation with stream sound not playing in mac

    Dear all,
    I have made a 5 min animation with stream sound. Its playing perfectly in PC. But in mac, its not playing. Stream sound starts from frame 60. So mac plays the swf plays till 60 frame, after that it pauses. I tried importing different sound format (wav, aif, mp3) and tried with all sound export setting but the problem remain same; its playing only till 60. When i removed the sound, it played till end. Even with event sound, it plays till end. But with stream sound, the problem. The problem is only in mac; in pc its perfect.
    I am using VMware Mac OS x leopard in window xp for testing purpose. I tested it in laptop with mac; but the problem is same. What could be the solution?
    Thanks in advance. Waiting for solution.
    Bhushan Pradhan
    spherenepal.com

    Dear all, I solved the problem myself. The problem was with the sound driver of mac. After installing sound driver, the problem is gone. Bhushan

  • Animation with motion path like flash

    Hi at all,
    is it posible to animate an object in circle move like motion path in flash?

    @resdesign
    If you were right, the example below won't work ;-)
    Rotation is  rotating an object around its origin. If the origin is outside the object, it moves in a circle.
    Here is the example: http://mcmm.com/edge/circular/circular.html
    It has been done like in my description above.
    All objects in the example are simply animated with rotation. The earth rotates around its origin and the planets do the same.
    The only difference between earth and planets is that the earth has its origin untouched while the planets have their origin outside.

  • Can i make Animations with Adobe Flash CS3 Professionals?

    can i make Animations with Adobe Flash CS3 Professionals? my
    goal is to make a Animation Serie But i got no Expereience!
    Is it any place i can learn how to use Adobe Flash CS3
    Professionals? Can i get a tutorial/training thing on
    www.adobe.com?

    Ha!
    Just scratch the surface by using the search functions on
    this site or google - thousands of
    websites that showcase flash animations since version 3 back
    in the late 90's - many websites have
    dedicated themselves to flash training and tutorials over the
    years.
    Basically, anything on the web that looks animated, right
    click over it and 9 times out of ten it
    will say "Flash".
    Chris Georgenes
    Adobe Community Expert
    mudbubble.com
    keyframer.com
    http://tinyurl.com/2urlka
    Arfusman wrote:
    > can i make Animations with Adobe Flash CS3
    Professionals? my goal is to make a
    > Animation Serie But i got no Expereience!
    > Is it any place i can learn how to use Adobe Flash CS3
    Professionals? Can i
    > get a tutorial/training thing on www.adobe.com?
    >

  • I need help with animation with progress bar.

    Hi,
    I need some help with creating something similar to this site (window opening animation with scrub bar):
    http://www.drutex.pl/pl/oferta/okna/okna-pvc/okna-pvc-iglo-5.html
    I'm kinda new to flash and all so some tutorials for such thing would be helpful.
    Thanks in advance
    Oscar

    What this will involve is a movieclip/timeline containing images showing the sequence of the motion (like the frames of a movie film) and a Slider component that changes the frame of that movieclip/timeline based on its position.
    Here is a link to an Actionscript 3 sample file that demonstrates a Slider providing the control of the timeline...
    http://www.nedwebs.com/Flash/AS3_Slider.fla
    You could edit the looks of the Slider component if you like by doubleclicking it and the inner parts you want to modify, or you could create one of your own if you have enough know-how to code it to work.

Maybe you are looking for

  • Can you actually buy a 3GS in Ireland?

    I'm starting to believe that the iPhone 3GS is just a myth here in Ireland. I've been trying to buy a pay-as-you-go 32GB black model since June without success. Last year, I tried to buy a 3G from June up until December and couldn't get one then eith

  • IPhone 4 and Windows 7 64 Bit

    Hi there, i got a Problem with my iphone 4 and my os windows 7 porfessional 64 bit. Last week my pc crashed and after 12 hours to find the problem (it was the memory... bloody things) i have allready deleted everything and partitioned the hd new. So

  • Adeyemi Fawole - Adobe Reader not working properly

    Hello, this is Adeyemi Fawole. I have a query, my adobe reader is not working properly and show an error 'not supported a file'. How I sought out this problem? Regards Adeyemi Fawole

  • Problems erasing window bootcamp partion using Disk Utility

    Hi guys, ive removed my windows partion before in the past without any hiccups, but this time i seem to have run into some problems. If i go into boot camp assistant, it wont let me proceed beyond the start menu. When i click continue it says "The st

  • Error accessing a web service

    I am getting the following error when trying to access a web service running on Tomcat. My client is running on WL7.1 and I used to clientgen to generate the client classes. unexpected encoding style: expected=http://schemas.xmlsoap.org/soap/encoding