OK, so you want to learn about JAVA. I'm a firm believer that the place to get started with any language is Hello World. So, with JAVA we are primarily concerned with Web programming, so what we want is a Hello World program which will display Hello World to a web page.
Exciting, huh?
Yes, but there are a few preliminaries to telling the web browser to say hello in an applet.
Unfortunately, we have to briefly mention a few of these items before diving in.
Java is Object Oriented
The hardest thing to get used to about Applet programming in JAVA, in my opinion, is the object oriented nature of the language. What we mean by that is that instead of creating a list of instructions for the computer to perform, we create objects with rules on how to respond to events. For instance, in a numerical program, the program structure is generally
read input
run model
print output.
Three simple tasks and then your done. In a JAVA program, you might instead want a program structure which says (IF MOUSE IS CLICKED ON RUN) run the model, (IF MOUSE IS CLICKED ON RESET) reset the model to initial conditions, (IF ...), and so on.
So, JAVA is object oriented, in that we are usually going to be more concerned about creating objects which react to input rather than creating a list of tasks to perform.
Java Code must be Compiled, but also Interpreted
For a beginning programmer it may seem a little strange that JAVA is code which must be compiled. That is, you create a set of instructions, and run a program which checks the logical accuracy of those instructions and creates an executable program. This is no different from programs like C/C++, FORTRAN, or BASIC, except for one added twist. In addition to needing to be compiled, JAVA code also has to be run by a special program on the machine. This is how JAVA runs on so many platforms, the "interpreter" is a different program on each machine, which takes a general JAVA executable, and runs it for that particular machine.
Java Applets need to be Embedded in a Web Page
Usually, this interpreter is accessed through your web browser, so the JAVA code needs to be set up in an HTML file to be read on the web. That means you either need to be able to do one of
two things, (a) create a local HTML file and read it in your browser using the "open file" option
avaialble in most browsers, or (b) have a public web space somewhere where you can put your
HTML file and java executables (or class files) so that you can browse to it on the web.
So what do we have so far?
Write JAVA code in such a way that it responds to events.
Compile the java code to create an executable file.
Write an HTML file which links to the JAVA executable, and place it on the web.
Run the JAVA code by viewing the web page.
There are finer points to all of these, of course, but that is as good a starting place as any.
On to the Code!
We start by defining our object and how it will behave. This one has very simple behavior, it displays hello world to the web page. A java program designed to run on a web page is referred to as an applet, and the first code will be....
(using your favorite text editor, such as vi, emacs, or pico in UNIX, or BBEdit on Mac, save this somewhere in your personal web space or in a file on your computer.
vi HelloWorld.java
import java.applet.*; // Use applet class library
import java.awt.*; // Use AWT class library
public class HelloWorld extends Applet { // Declare class HelloWorld as
// an applet
public void paint(Graphics g) { // Define paint method
g.drawString("Hello World",100,100); // Draw string to graphic
System.out.println("Hello Again."); // Draw string to console
} // End paint method
} // End HelloWorld class
Enter the above text, and save it as HelloWorld.java. Be sure to use the same filename as your class name, including capitalization.
Compile it in UNIX using the JAVA 1.0.2 compiler, /opt/jdk1.0.2/java/bin/javac HelloWorld.java
(save yourself some time here and create an alias to the java compiler, i.e. 'alias "javac=/opt/jdk1.0.2/java/bin/javac"', that way you only have to type javac HelloWorld.java.)
If you get any errors on compile, check your file and make sure it was entered in as above.
Once it runs, you should be able to do an "ls" and see a file HelloWorld.class.
Now, to view the class file, let's set up a simple web page.
vi HelloWorld.html
<HTML>
<BODY>
<APPLET CODE="HelloWorld.class" HEIGHT="200" WIDTH="200">
The applet should appear here!
</APPLET>
</BODY>
</HTML>
Open up your favorite browser, open the web page (see the
example solution) and see your first applet at work!
What it all Means
OK, let's break it down, line by line.
Import Statements
In HelloWorld.java, we start off with two import commands. What this does is tell the compiler what subset of all possible java commands you want to be able to use. Here we are using two very standard import statements, "import java.applet.*" and "import java.awt.*", for general applet commands, and for the AWT (Abstract Window Toolkit), which is a library of classes, or objects, for creating applets.
In general, expect to use four import statements in Shodor applets, the AWT and applet imports, org.shodor.utils for some common classes that we have created, and java.lang.math, for standard math commands.
Comments
Each of these lines contains a comment, denoted with two slashes. There are two ways of creating comments in JAVA: you can use the two slashes "//" to denote the rest of the line as a comment, or you can use a slash followed by an asterisk, which says that everything is a comment until you reach an asterisk followed by a slash, i.e. /* everything from here until the end of the comment is a comment. */
Class Declaration
OK, so we have import statements and comments, what is next? The first "real" line of code is the class declaration, "public class HelloWorld extends Applet{". The class is declared as public, meaning anyone can access it (this is important, what good does it do to make a class that noone can use), and is declared to extend the Applet class.
This could be translated into English as "I want to create a class of type Applet, with the modifications specified herein" or something like that. In computer-speak, this is referred to as inheritance. Rather than rewrite every possible thing applets need to do, your class inherits all of the properties of an applet, and you make changes as you need.
Override Paint Method
OK, so we have told the compiler we want the applet and awt commands, and we have defined a class called HelloWorld which inherits from the Applet class. The next line looks something like "public void paint(Graphics g){". What this is a function, or method, which exists in all applet classes, and which we are going to "override". Overriding a function means just that, we take the standard version of the function, and replace it with our own. The default paint does nothing, it just leaves the screen blank, so what we want to do is provide a new version of the paint function which does what we want it to do. Technically, this function belongs to our class, and when a function belongs to a class, we refer to it as a method.
Once again, the paint function is made public, as we may at some point want other parts of a program to be able to force the screen to redraw.
Access Graphics Context
The paint function is called with an argument Graphics g, which is a graphical device context that allows us to interact with the screen. It has a variety of methods associated with it which allow for drawing. In the first line of the paint function, we see how the Graphic method drawString is accessed, by calling g.drawString'("Hello World",100,100);', which goes to location x=100, y=100 on the display, and writes the string "Hello World" at that location. Pixels are defined as x=0, y=0 at the top left corner of the screen, and increase as you move to the bottom right corner. A 100 by 100 display is shown as an example:
Access Java Console
In addition to being able to access the display, sometimes we want to be able to just print out the value of a variable, particularly if we are testing a program, and want to see how a variable changes as the code progresses. Notice the next line, which is 'System.out.println("Hello Again.");'. Where does this go? Well, it depends on your browser, but on Netscape, go to communicator, tools, java console, and see what pops up. You should get a text window, which is where your System.out print statements go.
Make Sure all Brackets are Closed
OK, one last thing, which you probably already know. Notice all the brackets? They enclose pieces of code, so that the main set of brackets encloses everything being defined by the class deceleration, and the inner set of brackets encloses everything defined by the paint method.
And that, as they say, is that.
Exercises
Let's start off with the following.
Common Commands (which are hopefully more or less self-explanatory):
drawString(String text, int x, int y);
clearRect(int x, int y, int width, int height);
drawLine(int x1, int y1, int x2,int y2);
drawRect(int x, int y, int width, int height);
fillRect(int x, int y, int width, int height);
drawOval(int x, int y, int width, int height);
fillOval(int x, int y, int width, int height);
drawArc(int x, int y, int width, in height, int startAngle, int arcAngle);
fillArc(int x, int y, int width, in height, int startAngle, int arcAngle);
Replace the drawString command in Hello World with each of the above commands, and see what they do.
Using the above commands, create applets which display an image of the following: