Friday, January 4, 2008

How to create animations in JAVA

Introduction

In this article, we will discuss about all the basic concepts behind an animation application. The points discussed here may be well applicable to even the most serious commercial animation applications. This time, I have made use of Java as the development tool. While those who are already experienced in Java may also be benefitted by reading this article, I have made a conscious attempt to make this article simple to understand for those VB programmers who have the nerve (and I'm sure, as an Infoscions you have it) to accept this one as their first “Hello, World!” program in Java.

Watch the Animation Live...

Step 1: Extract all the files from the zip file here to a folder in your disk.

Step 2: If you do not have Java Development Kit (JDK) installation on your machine, install it from Infosys file server. Normally, you will see a folder named jdk1_2_2 in the Infosys file server inside which there is an installable version of the Java 2 SDK Standard Edition, v 1.2.2 (named jdk1_2_2-win). Double-click on the above file to start the installation. Just follow the installation instructions shown by the setup program keeping the default setup settings as it is. The Java 2 Runtime Environment (JRE) also will be installed on your computer as part of the installation. A detailed instruction on the installation is explained at http://java.sun.com/products/jdk/1.2/install-windows.html. You may not need to refer to it to try out the example here, but I suggest you go through the same for additonal knowledge.

Step 3: Goto Control Panel => System => Environment Variables and update the path variable to add the jdk executables directory in it (typically, C:\jdk1.2.2\bin). Now you are all set with installation of JDK and you will be able to compile and run any basic Java program (unless you make use of some special APIs in your code) on your computer. All the Best!

Step 4: To compile the sample program, go to the command prompt (run the command cmd) and move to the folder where you have extracted all the files in this article. Now, type in javac MahabharathaWar.java at the command prompt (ensuring that it is in the same case- Java is case-sensitive). The compiled version of the program will be a class named as MahabharathaWar.class. To run this class, type in java MahabharathaWar at the command prompt.

What's Behind the Scene?

Please go through the source code by opening the file MahabharathaWar.java in Notepad. Program first loads a set of .jpg files (mb1.jpg to mb25.jpg in our example) into an array of objects of type Image. Once loading is over, these images are painted onto a particular area of the screen after one with a delay of 300 milliseconds in between, thereby making the illusion of movement. This is the basic concept behind all the animation programs.

For my colleagues who are currently on VB, the following explanations may be helpful to understand the program better and to get interested in Java also (learning c# and migrating to VB.NET also would be easier if you do so).

  • In Java, there is no such thing as ‘global variables’, or any function that is not part of a class. Because Java is completely object-oriented, all Java code is inside a class definition. Our program has defined a class called MahabharathaWar. The name of the class must be the same as the name of the class (hence, we have MahabharathaWar.java as the file name). Java is case-sensitive, hence MahabharathaWar and Mahabharathawar will be considered as two totally different classes.

  • Much like in C, the program execution starts under a method called main which is defined under the class MahabharathaWar. The standard declaration format for main is public static void main(String args).

  • You can see that a new instance app of the object MahabharathaWar is created inside the method main using the statement MahabharathaWar app = new MahabharathaWar()¸ Creation of this new instance of the object MahabharathaWar in turn causes the class constructor method declared as public MahabharathaWar() to be fired (much similar to C++) automatically.

  • The class MahabharathaWar() is extended from a class called Frame. The statement super ("Mahabharatha War in Java"); in fact invokes the constructor method of the parent class Frame. We have used the above statement to set the title of the Window (much like form.caption in VB).

  • Java uses the concept of packages to control naming of classes. The import statements tell the compiler in which package to look for classes. In our example, we have 2 package declarations at the top. All Java programs are automatically assumed to use the java.lang package (which has the classes defined for all the commonly used objects in Java), but the compiler must be specifically instructed to use classes in other packages.

  • Abstract Windowing Toolkit (AWT) library is the basis for creating GUIs in Java. However, Sun came out with an improved library called Swing later, which is lighter than AWT since it makes use of Operating System specific calls for the construction of the GUI elements.

  • The java.awt.Frame class is the starting point for creating a graphical application using the AWT components. Hence you see that the class MahabharathaWar extends Frame. A Frame is a type of window equivalent to a VB Form having a title bar, menu bar, border etc. The extends keyword is used for specifying inheritance (which has no equivalent in VB6, but VB.NET will have it!).

  • The statement that starts with addWindowListener creates an anonymous inner class extending WindowAdapter and installing it as WindowListener. A class, which is a member of another class, is known as inner class (or nested class). An anonymous inner class is a class defined inside a single expression, having no name or constructor method.

  • The WindowClosing method is fired when user tries to close the window. It is much similar to the Form_Unload method in VB. The statement System.exit(0) causes the program to terminate.

  • The statement show() is equivalent to the from.show method in VB, it is used to display a window.

  • The statement setSize(645,295) sets the size of the window to be 645 pixels wide and 295 pixels high. It is equivalent to setting values for form.width and form.height respectively in VB.

  • The method System.currentTimeMillis returns a long primitive representing the number of milliseconds since 00:00:00 GMT January 1, 1970, a base time commonly used with Unix systems.

  • The statement repaint (30,55,580,130) asks AWT to redraw a particular portion of the frame starting from the coordinate (x, y) where x=30, y=55 for a width of 580 and height of 130.

  • The statement Thread.sleep(imageInterval) causes the program to sleep for imageInterval milliseconds.

  • The getImage method of the Toolkit class retrieves images stored in a disk, or a URL. Java supports GIF and JPEG formatted images through this method. The stetement images [i] = toolkit.getImage("mb" + Integer.toString (i+1) + ".jpg") loads a specified image into the image array named as images.

Conclusion

Through a silly animation program, I have tried to illustrate all the basic elements of more complex and entertaining animations. Also, we have touched on a number of important concepts in Java. Don't worry even if you could not grasp some of the concepts. But, surely make an attempt to explore the same and understand it further. Java is a true object-oriented language and knowledge of the same will really help you in learnig the future languages like C#, VB.NET very quickly. In the future articles, we will discuss about more advanced concepts in Java, like multi-threading.

As you might have noticed, my program has one serious problem. Unless you have a very fast computer and video card, you would have seen a lot of flickering during the animation. However, the good news is that this flickering can be avoided to a great extend by doing more coding. My program repaints only a standard portion of the screen by using the statement repaint (30,55,580,130), which repaints a relatively large screen area for each image. By selectively specifying the parameter values for the repaint method (so that only those small portions of the screens where there are differences in adjacent slides are repainted), you can control the flickering.

No comments: