简体   繁体   中英

Animation using Swing icon, numbered .jpg images, and for loop in Java

for(int i = 1; i < 65; i++){
diceLbl.setIcon(new  javax.swing.ImageIcon(getClass().getResource("/uhmonopoly/dice/2dice/2dice" + i + ".jpg")));
    diceLbl.repaint();
    repaint();
    diceLbl.revalidate();
    System.out.println(diceLbl.getIcon().toString());

    waiting(100);
    }

public static void waiting (int n){

    long t0, t1;

    t0 =  System.currentTimeMillis();

    do{
        t1 = System.currentTimeMillis();
    }
    while (t1 - t0 < n);
}

The above code changes the icon of the label from 1 - 65, for an animation of a dice roll, it works and prints out the result in the terminal window from System.out.println. in a slow way, but for some reason, the image on the GUI is not changing.

You should never use Thread.sleep(), or waiting() (a tight loop) in the Event Dispatch Thread. That prevents the GUI from repainting iself.

You need to use a Swing Timer to do the animation.

Read the Swing Tutorial . There are sections on "Concurrency" and on "How to Use Timers" that will explain the above in more detail.

One of two things (and possibly both) are happening here:

  1. In Swing, all actions relating to the GUI occur on a single thread(the event dispatch thread, or EDT). I can't be sure from the code you've shown but I suspect that the code you're sharing is executing on the EDT. When you call repaint and revalidate, Swing does not do either of those things immediately but rather schedules them to occur at the next available opportunity on the EDT. Because your code is executing on the same thread as the repaint is scheduled to occur on, no repaint can occur until your code completes(no mtter how long you wait).

  2. Your waiting method is doing something called busy-waiting . Basically, because you're constantly checking your loop condition to see if enough time has passed, other threads may not get a chance to execute(or they will execute inefficiently).

The standard solution to draw animation like this is to use a Timer to schedule the image changes. You can learn about Timers in Swing here: http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html

I also recommend you read up on concurrency in Swing here: http://download.oracle.com/javase/tutorial/uiswing/concurrency/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM