Friday, 16 April 2010

Using Thread in Java to Create Animation, Example 4

In the previous example we introduced a simple graphic work. We introduced a paint() method in a cosy corner to create the image we need without interfering with other parts of application. Then we call it back and forth in our thread tick-tacks. To render that graphic to realize the graphical object on our canvas1 we need an instance of java.awt.Graphics which is always present there from deep down the system and easily we catch it from the things that native methods create for us. It is like palette of painters with color pastes on it and different brushes. Once you catch an instance of that you can use it everywhere. The best is to take it from the container that you are working on it. Here I took it from the javax swing panel that I had on my Frame. Once you put the paint() on your canvas to remove it you have to repaint() your canvas; other wise its effect remains there and in the next tick-tack you have still there. In this way you have a moving brush that creates some other type of animation if you are interested. It is like a trajectory you are watching. In this example I have created that effect. Nevertheless, I have to repaint() my panel at each renewal of the thread when the trajectory reaches to the end of canvas, somewhere in isDone() method. You can de-comment and re-comment related instructions to watch its effect. This Blog is the simplest explanation you ever could find anywhere for java threading and painting and animation. Please, have a look at Example 4.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package Forward;

/**
 *
 * author Peter Jones
 */
public class Ex4Thread extends javax.swing.JFrame implements java.lang.Runnable{

    /** Creates new form Ex4Thread */
    public Ex4Thread() {
        super("Example 4!"); // A title for the frame
        T0=System.currentTimeMillis();
        x=X0;
        y=Y0;
        aPanel = new javax.swing.JPanel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(350, 120));
        add(aPanel);
        pack();
        start();
    }

    /** Start when browser is loaded or button pushed. **/
    public void start() {
        if (fThread == null){
            fThread = new java.lang.Thread (this);
            fThread.start();
        }
    } // start

    /** The thread loops to draw each frame.**/
    public void run() {
        j=0;
        // Loop through animation frames
        while ( fThread != null){
            // Sleep between frames
            try{
                Thread.sleep (1);
                t=System.currentTimeMillis()-T0;
                t=t/1000; //convert to seconds
                x=(int)(V0*t);
                y=Y0+(int)(G*t*t/2);
                paint();
            }
            catch (InterruptedException e) {break; } //break stops the loop
            // Now go to other frame
            other();
            isDone();
        //if (this.isDone()) fThread = null;
        }
    }// run ends

    // Your other frame comes here.
    public void other(){
        //
        ++j;
        // Sleep between frames
        try{
            Thread.sleep (1);
            //aPanel.repaint(); // meanwhile repaint the panel.
        }
        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;
            T0=System.currentTimeMillis();
            x=X0;
            y=Y0;
            aPanel.repaint();
        }
    return temp;
    }

    //Create some graphic
    public void paint() {

        java.awt.Graphics g=aPanel.getGraphics();
        g.setColor(java.awt.Color.red);
        g.fillOval(x, Y0, 2, 2); //Object one (aircraft)
        g.fillOval(x, y, 2, 2); //Object two (released bomb)
       // g.setColor(java.awt.Color.gray);
        //g.fill3DRect(300, 80, 15, 30, true);

    }

    public static void main(String args[]) {
        new Ex4Thread().setVisible(true);
    }

    /* Variables declaration - do not modify
     * For simple GUI
     * For thread animation
     */
    private javax.swing.JPanel aPanel;
    private Thread fThread;

    /* Variables declaration - do not modify
     *
     */
    int j=0; //counter
    final int COUNTS=3500;

    double t=0; //seconds
    double T0=0; //seconds

    int x=0; // X-coordinate of a point
    final int X0=10; // pixels

    int y=0; // Y-coordinate of a point
    final int Y0=10; // pixels

    final int V0=25; // pixels/second
    final double G=0.98; //pixels/second/second
    // End of variables declaration
}// End of class
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.
The first trajectory is simple and similar to previous one. It hs a constnt speed of V0=25. Second trajectory follows some rule of mathematics as y=(1/2)g.t2 It is an aircraft bomber with speed of 25 pixels per second and releases a bomb. I assumed the gravity should be one tenth of the earth gravity. It is 0.98 pixels per second per second. x-ccordinate of the bomb remains the same as x-coordiate of the bomber aircraft, that is x=V0*t,  but its y-coordinate changes according to law of gravity.
It is important that you make a formula such that it could be cosistent with the dimensions of canvas. You also should consider for how long your frame remains in the sight. For that it is necessary, too, to know how long the effect of an exposure remains in the eye. It is 20 milli second.

==================================
1. I mean canvas of painting. I do not mean Java AWT Canvas.

No comments:

Post a Comment