Part 2: Java in (some) Detail

Object-Oriented Programming
The Applet Creation Cycle: Hello World
From Static Text to Animation: Threaded Applets
More Threaded Applets: Ticker Tape Applet
Flicker-Free Animation: Drawing Offscreen
Adding Event Handlers to an Applet
GUI - Adding a Graphical User Interface
The Finished Product
More GUI - Windows and Menus
What's Next

Object-Oriented Programming

Java is an object-oriented programming language. Instead of building a program around a set of interrelated procedures, you use data sets and affiliated methods, collectively called classes. Java incorporates all the necessary concepts of any object oriented language:

Classes
The fundamental structure in Java. Classes are similar to structured types in C, or to record types in Pascal, with some extra features. All functions and procedures are associated with classes, and there are no 'stand-alone' procedures.
Instances
Similar to the value of a structured type. In Pascal, there is the TYPE of a record, and a variable could be of that type. In Java, there are classes, and a member of a class is called an instance of that class. At the time a class is instantiated, memory is allocated and the class is initialized, using the class constructor.
Inheritance
Language construct that allows for classes to be related to one another so that a subclass can inherit features of its superclass. For example, you can define a class VEHICLE, with a couple of associated methods, and then define a CAR as a subclass of a VEHICLE. In that case, all methods and attributes valid for a VEHCILE will automatically apply to CAR as well. While a class can inherit properties from another class, multiple inheritence is not possible in Java (but an alternative mechanism is available).
Encapsulation
Language construct that enables programmers to limit access to parts of a program. A programmer can provide an abstract object such as a STACK, that allows certain operations such as PUSH and POP, but the programmer can completely protect the actual implementation or inner workings from public access.
Overloading
The ability to use the same name for multiple methods (Java methods are similar to C or Pascal functions and procedures). The only requirements are that the type of arguments are different for procedures with the same name. For example, a class could have one method DoubleIt that takes an integer as input, and another method also called DoubleIt that takes a string as input. The selection of the correct method is based on the types of the arguments in the calling expression.
Polymorphism
Ability to deal with multiple types based on a common feature. In standard programming, one procedure can only operate on a specific set of argument types. Polymorphism allows you, on the other hand, to define a method that applies equally to different arguments, as long as they share some common features.

Of course, Java has the usual standard variable types such as Double, Integer, String, and Boolean (but no Pointers), IF-THEN-ELSE contol, loop structures, array structures, and more. The actual language is closely related to C++, and it is best learned, for our purposes, by example.

The Applet Creation Cycle: Hello World

Let's start to write our first Java applet. All it is supposed to do is to display the string "Hello World". Actually, to be more flexible, our first applet is supposed to display any string that is specified as a parameter. You can use any text editor to create the source code. Since our goal will eventually be to create a ticker tape applet, we will name our first application ticker1.
Ticker 1 Source Code
Ticker 1 Applet

The same program, with some explainations in italics.


import java.applet.Applet;       loading Applet class definitions
import java.awt.Graphics;        loading Graphics class definitions

/** Defining main applet **/     a comment

public class ticker1 extends Applet  new public class, inherits 
                                     properties from Applet class;
                                     every applet has methods such as 
                                     init and paint that will be called
                                     at the appropriate time automatically
{      
    String input_text;    Defines String variable input_text

    public void init()    method that is called when class starts;
                          it overrides the init method of a general Applet
    {   like a BEGIN in Pascal
        input_text=getParameter("text");  reading the value of the parameter
                                          text and storing it in input_text
    }   like END in Pascal

    public void paint(Graphics g)         painting method; overrides the paint
                                          method of a general Applet and is called
                                          automatically. Has a Graphics object g as
                                          input.
    {
        g.drawString(input_text,50,25);   Method from the Graphics class that
                                          will draw a string at the inidicated (x,y)
                                          position.
    }
}

After typing this source code in, save it to a file called ticker1.java on disk. From the DOS prompt, you can now compile the program by typing

   \bin\prg\java\bin\javac ticker1.java

assuming the Java compiler is in directory \bin\prg\java\bin\javac. If that directory is in your path, you could of course type javac ticker1.java only. In any case, if you made no errors, this will create the byte-code applet called ticker1.class. To use that class, use your text editor to create a simple HTML file such as the following:



<HTML>
<HEAD>
<TITLE>Ticker 1</TITLE>
</HEAD>
Here is any HTML code you like. And here is:
<APPLET CODE="ticker1.class" WIDTH="150" Height="25">
    <PARAM NAME="text" VALUE="Hello World!">
<B>Your browser can not handle Java applets</B>
</APPLET>
<HR>
</BODY>
</HTML>

If you load this file with a Java-aware applet, you will see the words "Hello World!" that are displayed by the applet inside your browser. The line with HTML code between the APPLET tags is ignored. If you want to display a different string, you could change the value of the TEXT parameter in the HTML code.

If your browser was not Java-aware, it would ignore the APPLET and PARAM tags, and instead display the line of HTML code.

In this way, you can write HTML code that works one way on Java-aware browsers, and still looks good when viewed with non-Java aware browsers.

The above applet could be modified to draw graphical objects as well, by simply adding code to the paint method. There are methods such as g.drawLine, g.drawRec, g.fillRec, etc. Check the appropriate class for all methods that are allowed here. Remember, our class inherits from the Applet class all methods that are valid for the applet class, and since we import the Graphics class, we can also use the methods of that class on our Graphics object g.

From Static to Animation: Threaded Applets

Now we would like the string to change color every second to some random color. In BASIC or PASCAL, you would probably use some pause feature for a second pause before changing color. This is not a good approach here. Our Applet will run concurrently with other applications, so a PAUSE statement would actually take up processing time. Even pausing in BASIC takes up processing time. Instead, we will use threads because Java has exceptionally good support for threads. Threads are Java's way to implement multitasking. Each thread is allocated a slice of processing time, and hence multiple threads can execute seemingly concurrently. In our case, we will only use one thread, but it executes concurrently with any other applications that are running at that time on the system.
Ticker 2 Source Code
Ticker 2 Applet

More Threaded Applets: Ticker Tape Applet

Changing colors may be nice, but now we want to have an actual ticker-tape applet that moves text from the left to the right and then repeats the process. Our threaded applet from above needs just a few modifications to accomplish that. Here is the new applet:
Ticker 3 Source Code
Ticker 3 Applet

Flicker-Free Animation: Drawing Offscreen

What is still bother is that the animation flickers, which is particularly noticible on slower computers. This is due that the actual painting of the screen takes place in 'real time', while the user can see it. It would work a lot better if we first create the complete image where the user can not see it, and then 'swap' that image with the one currently being displayed.

That standard technique for flicker-free animation uses an offscreen image to contain the image while it is being constructed, and then we replace the screen image with the offscreen, finished image (which is a fast operation). That technique will eliminate the flicker in many animations. Here is the applet code:
Ticker 4 Source Code
Ticker 4 Applet

Adding Event Handlers to an Applet

My current ticker tape applet is not bad, but I would like to be able to start and stop it by clicking the mouse inside the applet area. That is easily accomplished by redefining the standard event handler for mouse events that every applet has.

Here is the source code:
Ticker 5 Source Code
Ticker 5 Applet

GUI - adding a graphical user interface

Since it is not obvious to people that they can use the mouse to stop and start the ticker type, I would like to add some buttons.

Java has predefined layout managers that you can use to layout different components of an applet. We will use two in our next refinement, Flow Layout and Border Layout.
Ticker 6 Source Code
Ticker 6 Applet

The Finished Product

Just to be complete, here is a possible finished version of our ticker tape applet.
Ticker 8 Applet

More GUI - Windows and Menus

The final applet we want to look at is embedded in a web page, but can open up its own parent window. You could draw into that new window, and even control it from the parent window. That new window can even have menus, like a standard Windows application.
GUI Example Source Code
GUI Example Applet

What's Next

We did hopefully cover the essential steps in creating Java applications, and by showing an example using threads and offscreen drawing you should be able to implement many of your own Java applets.

However, there were many things we did not cover at all:
Multi-threaded applications
Syncronizing multiple threads
Input Streams (reading data from a file into an applet)
Output Streams (writing data to file from an applet)
Built-in Network support

Some of those topics can be picked up by reading either one of the two books that were used to put together this workshop:

Essential Java by Jason J. Manger, McGraw Hill
covers JavaScript and Java, has a lot of example on enclosed CD; for intermediate to advanced HTML people
Java by Example by Jerry Jackson and Alan McClellan, SunSoft Press (A Prentice Hall Title)
focuses on Java, has several sophisticated examples and Symantec's Java Cafe Light on enclosed CD; for the intermediate to experienced programmer

More details can be found at the API pages that explain all classes an their methods in details. You should install those pages, together with a tutorial that is also available from SUN at http://www.javasoft.com/.

(Bert G. Wachsmuth)