Wednesday, 7 April 2010

Using Thread in Java to Create Animation, Example 2

We could run the thread by tick-tacking between the run() method and an auxiliary other() method, each take the thread to a certain sleep duration. You can test if you can remove the sleep from the other() method. Still you have tick tack but not smooth to create animation. The high of the clock pulse is equal to run() duration say 100 ms but the low (I measured using system time) is 3 to 4 milliseconds. you can add yet another anOther() method and a third image in your resources and get a better effect. you also can play with sleep duration to reach more smoothness in terms of visual subjective effects. you can consider the duration of effect when human eyes switches between two scenes. Now I make a more complex animation. I make these like the old neon lamps rather than using maths calculation and rendering graphics. If I use painting then my attention would be diverted to force correctness of java codes when running in hand in hand with the native operating system. That frequently needs adjustments which is not related to the job of animation. I should be confident that my animations work and encourage me to step forward rather than becoming disappointed. Then I can add other elements to them. This example put pieces of a whole picture consecutively and creates animation similar to the book-flicking through animation that children make using corner of pages of a book.

package Forward;

* author Peter Jones
public class Ex2Thread extends javax.swing.JFrame implements java.lang.Runnable {
    /** Creates new form Ex2Thread */
    public Ex2Thread() {
        aPanel = new javax.swing.JPanel();
        aLabel = new javax.swing.JLabel();
        setPreferredSize(new java.awt.Dimension(50, 110));
    /** Start when browser is loaded or button pushed. **/
    private void start() {
        if (fThread == null){
            fThread = new java.lang.Thread (this);
    } // start
    /** The thread loops to draw each frame.**/
    public void run() {
        // Loop through animation frames
        while ( fThread != null){
            s = mString(j);
            // Sleep 100msecs between frames
                Thread.sleep (100);
                aLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource(s)));
            catch (InterruptedException e) { }
            // Now go to other frame
            //if (this.isDone()) fThread = null;
    }// run ends
    // Your other frame comes here.
    public void other(){
        // Sleep 100msecs between frames
            Thread.sleep (100);
        catch (InterruptedException e) { }
    // Boolean allows you to terminate this thread, if you like, and go to other tasks.
     // I used it to provide a flag for counting.
    public boolean isDone() {
        boolean temp = false;
        if(j == COUNTS) {
            temp = true;
            j = 0;
    return temp;

    // This method creates strings "Sun0.gif", "Sun1.gif", ..., to "Sun7.gif"
    public String mString(int n){
        String aSt = "";
        aSt = "Sun".concat(java.lang.String.valueOf(n)).concat(".gif");
    return aSt;

     * Next main
    public static void main(String args[]) {
        new Ex2Thread().setVisible(true);
    // Variables declaration - do not modify
    // For simple GUI
    private javax.swing.JLabel aLabel;
    private javax.swing.JPanel aPanel;
    // Variables declaration - do not modify
    // For thread animation
    int j = 0;
    String s = "";
    Thread fThread;
    final int COUNTS = 8;
    // End of variables declaration
Click here to see the application. If you save the "jar" file in your computer you can use "7z" decompression utility to extract source file and image files.
I took small image of "Helios" (Sun personified) in form of an icon. I used the Windows(R) Paint utility and sliced the icon in desired forms. In this way I got eight icons; from "Sun0.gif" to "Sun7.gif". I could make an array of images but I preferred to create a method mString(int n) to fetch the icons one after the other. Then I adjusted my counter from zero to seven to bring images one after another andput them on the java swing label. I could terminate the animation here and go to other jobs by calling isDone() method within the "if" statement and killing the thread; instead of that, I reset my counter back to zero to start it again. I used the isDone() method in a void type fashion. You know in java many boolens can work as void as well without their return value becomes utilized. Hence, I commented the "if" to prevent killing the thread and keep the tick-tack going on and on. If you un-comment this line and comment "j=0; statement" in the isDone() method, then the animation runs only once.
You can also put the "++j" before call to the other() method inside the run() method and then make the call to other() method commented and see the effect. It works but not as smooth as before. Best is to give your clock one tick and one tack; one run() and one other(). Then go and adjust the desired timings inside each state of the run() and the other().

No comments:

Post a Comment