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.

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.

0 comments:

Post a Comment