A Tweak of Lemon...

Blowing away the clouds in the coffee..Brewing the first Applet

"Ours is the age of substitutes; instead of principles, we have slogans; instead of genuine ideas, bright ideas; instead of languages, jargon. "

When it comes to bright jargon, Sun Microsystems has left no stone unturned. And the creative terminology goes a long way (if not all the way) in making it like the tidal wave it has been. Java programs are called 'Applets'. In the directory in which the whole downloaded software of Java is saved, there is a subdirectory called Bin. This is where we have the Java compiler called 'Javac.exe'. The first thing we do is to create a subdiretory under the root called, say, "xxx". Then set the path to \java\bin. We are going to write our Applets here. Each applet or program has to be written in a file with the extension of .Java. In keeping with the ritual, let us consider this one-liner code first...

a1.java
class zzz
{
}

You'll agree that even an ice-hockey player or a visitor to Disneyland will love this sort of a program because it is looks manageably concise and absolutely simple. Well, we do not expect fireworks with that sort of a code, but let us compile it all the same. Save the file a1.java. It is noteworthy to mention here that like C/C++, Java is case-sensitive too (and preposterously so!). Type the command javac a1.java. The compiler gives no errors. If you key in the DIR command now, you will see that after successful compilation, a file called zzz.class is made automatically. That is because we specified zzz as the name of our class. This makes it adequately clear that the name of the applet file (the .java file) and the class can very well be different.

Now comes the question of viewing how our applet works. If it is a Java applet, you can call it only from an HTML file (An HTML file, in case you don't know, is nothing but a text file with tags that link it to other documents). Since all the documents on the Internet use this format, an applet has to be specified in an HTML file. Consider the following HTML file.

aa.html
< applet code = "zzz"  width =120 height =120></applet>

As is evident, the .class file (zzz.class in our case) that is formed after successful compilation of the .java file (a1.java) is specified in the HTML. The width and the heigth This is the way in which you can incorporate an applet in the HTML format. The applet could be a program to display animation or perform any other dynamic task and thus, enliven a page on the net.

But it still remains to be seen how the applet works or what the output looks like. Towards this end, we have a program called the appletviewer (in the same directory as javac). This is a program that allows you to view how your applet works. Hence, we key in the command appletviewer aa.html. Sorry folks, but there is no output (if your stars are not happy with you, your machine might even hang!).

There are a hundred and sixty five things to be done in the background before our class begins work (like the initialization routines et al). Our class does not have any property towards that end. As one does not know what routines are to be initialized internally, the safest thing to do is to derive a class from another class provided with the language. Now edit your a1.java file in the following way.

class zzz extends Applet
{
}

Applet is a class that has all the required functions necessary for this purpose, so we derive zzz from Applet or extend zzz to Applet. This means, in plain English, that we can now use all the functions and variables of the Applet class and also add our own ones. The only hitch now is that compiler refuses to recognize Applet, unless we mention specifically the name of the class library in which it is contained. So we now have to formally introduce the compiler to the Applet class. We do this by inviting the Applet class into our program (how else?). Only, the invitation here is in the form of importing a file called Applet.class from the classes\ java\Applet subdirectory.

import java.applet.*
class zzz extends Applet
{
}
When we compile this program, however, we get some lines of dreadful errors, with only one making any sort of horse-sense, " ; expected". Guess what, we missed out on the elusive semicolon after the import statement! Remember, this is a sibling of C and C++ and the use of semicolon is inevitable. And hence, our program now looks like this...
import java.applet.*;
class zzz extends Applet
{
}
However, having put that necessary punctuation, when we compile and run the program again, it gives the error that the 'class not public'. As a result, the applet is not initialized. That brings us to another important feature of the Java, as it stands today. All the classes that we define have to be public, otherwise the class cannot be initialised by the Appletviewer. Not being the arguing types, we make our class public in the following way...
import java.applet.*;
public class zzz extends Applet
{
}
One snag with making a class public is that the name of your file and that of the class have to be the same. So after adding the word public, rename a1.java to zzz.java. Before you begin to swear about this queue of unending snags, let us state that this is it. We finally have what can be safely labeled as the smallest Java program. Now when we key in the command appletviewer aa.html, a small window appears to show the output. This is the first successful applet and all the economists out there would love it. Because it is concise, precise and absolutely useless ( :-) ). As we are not economists and expect our applet to do something, let us make some additions. But to continue further, we have to quit from the appletviewer. For this, click on the Applet menu that you see in the appletviewer window and select Quit.
import java.applet.*;
public class zzz extends Applet
{	public void init()
	{	resize(300, 500);
	}
}
All the functions in our class have to be public. The function init() gets called initially when you run an applet. Whenever your applet begins and you need to do something put it in the init(). Inside this, we have the resize() which is one of the many functions of the Applet class. It is used to change the size of the area in which our applet can work. By default, a small area is given to the applet but the resize() says "Give me two parameters, the width and the height and I can increase or decrease the scope of your applet". We obediently pass two parameters to this function, the width of the area(300) and the height(500). When we compile and run the above program, we can see a rectangular box as an output. As yet, we have just plain specified the area for the applet, now let us try displaying something inside it...
import java.applet.*;
import java.awt.*  ;
public class zzz extends Applet
{	public void init()
	{	resize(300, 500);
	}
	public void paint(Graphics g)
	{	g.drawString("Hello", 10, 50);
	}
}
As you must have realized, this program displays "Hello" at the coordinates 10, 50. As mentioned earlier, the init () gets called first. The workarea is resized in the same way as before. Everytime the screen or the window has to be displayed, the paint() gets called. You cannot set your watch by it. An object g that looks like the class Graphics has to be tagged along as a parameter. As Graphics is a predefined class, we require to import the Graphics class, (which is in the java\awt\Graphics subdirectory). The Graphics class has many functions including the drawString(). Give this function its due in the form of three parameters, the string to be displayed, and the x and the y coordinates and promises to display the string at that position. So when the paint is called, "Hello" appears on the screen.

Now that we are aware of the method of displaying, let us write a program that is a little more interesting. We propose to display a string and a value everytime the Mouse is clicked. Key in the following code...

import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{	int i;
	public void init()
	{	resize(300, 500);
	}
	public void paint(Graphics g)
	{	g.drawString("i....." + i, 10, 50);
	}
	public boolean mouseUp(Event e, int x, int y)
	{	i++;
		repaint();
		return true;
	}	
}
Let us start from the very beginning. A variable i is defined before any other function. This make sure that the variable can be used in any function (for you C++ programmers out there, it is similar to a public variable). A very interesting feature is the mouseUp(). Every time you click with the mouse, the mouseUp() gets called. The mouseUp() is counted upon to return a True or false. And that is the reason why that ugly word 'Boolean' comes into picture (which will be explained at a later stage).Note that the mouseUp() accepts three parameters. The Event is irrelevant to explain at this point of time and it will be explained later with an useful example. The other parameters are x and y coordinates, which are internally calculated everytime the mouse is clicked. That is, if i click at, say, the position (15, 20), then the value of x will automatically become 15 and that of y will be 20. With every click the value of i is increased by 1. Then the repaint() is called, which in turn calls the paint(). This way, with each click we display the string "i...." followed by the value of i. The drawString() takes care of that. Note the plus sign (+), it is used to concatenate or join two strings to be displayed.

They said programming in Java is object-oriented and event-driven. That sent my brains for a toss when I first heard it, but the above program bears a glittering testimony to that. The function mouseUp() gets activated everytime the mouse button is clicked, the paint() is called whenever a window or a screen has to be redrawn etc.

Let us alter this code to display our usual "Hello", but now at the coordinates where the user clicks. Change the code in zzz.java as the following..

import java.applet.*;
import java.awt.*  ;
public class zzz extends Applet
{	int a; int b;
	public void init()
	{	resize(300, 500);
	}
	public void paint(Graphics g)
	{	g.drawString("Hello", a, b);
	}
 	public boolean mouseUp(Event evt, int x, int y) 
	{	a=x; b=y;
		repaint();
		return true;
	}
}
Here, a and b are public variables as they are defined outside all the functions. When a variable is public, it can be used inside any function. The logic to the above applet is pretty simple. Everytime the mouse is clicked, the mouseUp() function is called. We can get to know the coordinates where the user has clicked because the coordinates are stored automatically in x and y. These values are assigned to a and b. Now when the repaint() is called, it calls the paint(). Here, the drawString() will display "Hello" at the specified position. But since the specified coordinates are nothing but the coordinates of the place where the user has clicked (a and b), "Hello" will now be displayed at the position where the user clicks.

Our next program draws a line between two clicks of the mouse. That is, a line is drawn between the first and the second click, the third and the fourth click and so on.

import java.applet.*;
import java.awt.*  ;
public class zzz extends Applet
{	int a; int b; int c; int d; int e;
public void init() { resize(300, 500); } public void paint(Graphics g) { g.drawLine(a, b, d, e); } public boolean mouseUp(Event evt, int x, int y) { if (c==0) { a=x; b=y; c=1; } else { d=x; e=y; c=0; repaint(); } return true; } }
We define five public variables a, b, c, d and e. Then the paint() is called by default for the first time. It is passed four parameters, the x and y coordinates of the points between which the line has to be drawn, i.e. the two endpoints of the line. But since the four variables a, b, d and e are currently zero, there is no line displayed. Whenever the user clicks with the mouse, mouseUp() functions gets called. A variable c takes care of the fact whether the click is for the first or the second time. If the click is for the first time (i.e if c is 0), a and b are given the value of x and y. These are the points of the first end of the line. Then c is made 1. The second time the user clicks, c is 1. Therefore, d and e given the values of x and y. c is made 0 again. And the repaint() is called. Now when the paint() is called by the repaint(), the drawLine() will draw a line from (a, b) - the position of the first click, to (c, d) - the position of the second click. In this way, the value of c can be alternated and a line drawn between two successive clicks.


If you are not under the guillotine, whisk to the next topic "Making the clouds look good" or just fling your comments, feedback, suggestions et al to us right offhand...

Back to our Java page


Vijay Mukhi's Computer Institute
B-13, Everest Building, Tardeo, Bombay 400 034, India.
http://www.neca.com/~vmis
e-mail : vmukhi@giasbm01.vsnl.net.in