Anyone Else for Java?

If you don't see a title in changing rainbow colors at the top of this page, your browser does not understand the Java language. Try the latest version of Netscape or HotJava!

Session 1 - April 30, 1997:
Building with Objects and Responding to Simple Events


Assuming your browser is Java-enabled, the main title of this page, with its changing colors, has been implemented by a Java program called an applet. An applet runs in a browser such as Netscape or HotJava. We will need to learn a little HTML for this course, but only enough to post a Java applet on a page. Let's look at the HTML code that is needed to run RainbowText.


Putting an Applet on a Web Page

Start a text editor like Notepad or WordPad (or even Word) and either type in, or copy and paste the following text:

<applet codebase="http://www.journey.sunysb.edu/MoJA/"
code="RainbowText.class" width=400 height=100>
</applet>


Save this as a text file called RainbowText.html. Open it in your browser and look at it. You should see:


The above example uses the RainbowText applet without obtaining a local copy of it. If you place a copy of the RainbowText.class file in the same directory as your HTML file, your code can be shortened to:

<applet code="RainbowText.class" width=400 height=100>
</applet>


Using Parameters for Flexibility

What could you do if you wanted to display a string other than RainbowText? If the author of the applet programmed in some parameters, you can use them for flexibility. In order to use the parameters, you need to know their names and what kind of data you can use for their values. Try this in your html file and take a look at the results in your browser by opening the html file again in your browser (Simply reloading probably won't work.):

<applet codebase="http://www.journey.sunysb.edu/MoJA/"
code="RainbowText.class" width=400 height=100>
<param name=text value=CHiPR>
<param name=fontsize value=72>
</applet>

If you would like to experiment with other parameters that RainbowText has implemented, you can find a description of them on the RainbowText page.


Let's look at the Java code for a really simple applet:

/* Say hello to the world. */ import java.applet.Applet; import java.awt.*; public class HelloWorld extends Applet { public void paint(Graphics g) { // What to put on the screen g.drawString("Hello, World!", 10, 20); } }

Now let's see what it looks like on the screen:


This is what each line does:
/* Say hello to the world. */
This is a comment for the benefit of a person reading the code itself. It is essentially ignored by the compiler that translates the program into the bytecode that the browser runs.
import java.applet.Applet;
This statement provides us with a shortcut name that we can use to refer to the java.applet.Applet class that is part of the Java environment. We can now call it by the name Applet. We need this class in order to create our applet.
import java.awt.*;
We need a class called java.awt.Graphics in order to draw text on the screen. Classes usually come in packages. java.awt.Graphics is in the java.awt package. If we use a * instead of the name of a class in our import statement, we make the shortcut name for all classes in that package available to us.
public class HelloWorld extends Applet {
Here, we name our class and declare it as public. The public modifier enables anyone using the HelloWorld.class file to access the HelloWorld class that lies within. This is necessary so that the browser can find our class. Sometimes we may declare a class as private, so the messy details are hidden from programmers who use the file. We will talk more about information hiding later. For now, let's remember that when you create code to give to someone else, you usually don't want them to have to deal with the details of the code. Instead, you specify an interface for them, such as the parameters that they can use, and you hide the messy stuff. Remember that when you buy a coffee maker, you don't want to have to learn all the technology that went into it in order for it to be built. You want to know how to put the ingredient in, how to plug it in and work the controls, and how to get the ingredients out.
public void paint(Graphics g) {
Now we begin to declare a method called paint that is part of our HelloWorld class. The method is public so the browser can use it draw our text on the screen. It does not return a value such as a number, a text string, or anything else at all, so we declare it as void. Its purpose is to do something, namely draw on the screen, rather than to return information to the program. The browser looks for the paint method for a component whenever it has to render the component on the screen. Therefore, we can write the paint method to draw what we want, and it will get done.
// What to put on the screen
This is a one-line comment. It is delimited on the left by a // and is assumed by the compiler to end at the fist line break after that.
g.drawString("Hello, World!", 10, 20);
This statement draws a text string on the screen. g was declared as a parameter on the first line of the paint method. It is a reference to the Graphics class, since it was decalred that way. The Graphics class contains a number of methods that can draw on the screen, including drawString, which, as its name suggests, draws a string on the screen. The Graphics.drawString method takes three parameters, which, in order, are:

a string
the string to be drawn
an integer
the distance from the left margin of the applet (or other component) to the place where the string will begin
another integer
the distance from the upper margin of the applet (or other component) to the point where the lower-left corner of the string will be located
}
This closing curly bracket matches the opening curly bracket for the paint method, and marks the end of the code for this method.
}
This closing curly bracket matches the opening curly bracket for the HelloWorld class, and marks the end of the code for this class.

In a Class of Our Own

A Java applet is composed entirely of classes. You can think of a class as a template for a particular type of object, such as a car. An object is characterized by attributes and methods. In the case of a car, attributes include color, number of doors, horsepower, manufacturer, year, and model. Methods are often actions, that, in the case of a car, would include go, stop, accelerate, turn, start the windshield wipers, and stop the windshield wipers.

We need to make a distinction between a type of object and an individual example of that type of object. For example, the word Car refers to a type of object, so Car is a class. A particular car, such as my 1988 Subaru Justy, is an individual example of a Car. In Java, I would call my car an instance of the class Car. When we name classes in Java, we traditionally start the name with an uppercase letter. However, instances of classes are referenced by instance variables, and the names of these variables traditionally start with lowercase letters. Names of methods also should start with lowercase letters.

The actions of methods can be modified by parameters. For instance, a turn can be to the right or the left, and should also specify a number of degrees. Windshield wipers can be put on intermittent, slow, or fast. In a Java implementation of a car, you might have a statement like carThree.turn("left", 90). carThree that uses method turn to tell an instance of a Car called carThree to turn and passes "left" and 90 to the turn method as parameters. carTwo.turnOnWipers("front", 3) might tell carTwo to turn on its front wipers at speed 3.

In order to make this discussion less abstract and more real, we will now create a class and then use it in an applet. The applet will create and use four instances of this class. Let's get into the habit of thinking about programming in terms of classes.

Suppose we want to create a class that can keep track of weather statistics for a locality on a given date. We can define the following class:

// WeatherData.java
import java.awt.*;
public class WeatherData {
  // the data
  private String locality;
  private String month;
  private String day;
  private String year;
  private int highTemp;
  private int lowTemp;
  private double precipitation;
  private double pressure;

  // constructor method creates an instance of the WeatherData class and initializes it
  // a constructor has the same name as the class
  public WeatherData(String locality, String month, String day,
            String year, int highTemp, int lowTemp, double precipitation,
            double pressure) {
    this.locality=locality;
    this.month = month;
    this.day = day;
    this.year = year;
    this.highTemp = highTemp;
    this.lowTemp = lowTemp;
    this.precipitation = precipitation;
    this.pressure=pressure;
  }

  // display method that puts the data on the screen
  public void display(Graphics g, int xloc, int yloc) {
    g.drawString(locality, xloc, yloc+10);
    g.drawString("Date: "+month+" "+day+", "+year, xloc, yloc+20);
    g.drawString("High: "+highTemp,xloc, yloc+30);
    g.drawString("Low:  "+lowTemp,xloc, yloc+40);
    g.drawString("Precipitation: "+precipitation, xloc, yloc+50);
    g.drawString("Pressure: "+pressure, xloc, yloc+60);

  }
}

The name of the file containing the class must be the same as the name of the class, with a .java extension added. Therefore, WeatherData.java would be the name of our file.

Now, how do we use our new class? We will write an applet that creates and displays four instances of the WeatherData class.

import java.applet.Applet;
import java.awt.*;
public class WeatherApplet extends Applet {
    // Declare four instance variables of the WeatherData class
    public WeatherData locationOne, locationTwo, locationThree, locationFour;

    public void init() {
        // Initialize the four instance variables
        locationOne = new WeatherData
             ("Stony Brook, NY", "March", "12", "1997", 70, 55, 0.0, 30.10);
        locationTwo = new WeatherData
             ("Ross Ice Shelf, Antarctica", "March", "12", "1997", 5, -22, 0.6, 29.95);
        locationThree = new WeatherData
             ("Upper Mantle", "March", "12", "1997", 1000, 999, 0.0, 1800000.0);
        locationFour = new WeatherData
             ("Inner Core", "March", "12", "1997", 3001, 2999, 0.0, 9000000000.0);
    }
    public void paint(Graphics g) {
        setBackground(Color.cyan);
        g.drawString("The CHiPR Weather Report", 10, 10);
        locationOne.display(g, 10, 30);
        locationTwo.display(g, 250, 30);
        locationThree.display(g, 10, 130);
        locationFour.display(g, 250, 130);
    }

}

The following HTML code can display the applet:

<applet code="WeatherApplet.class" width=500 height=200>
</applet>

The following display results when the HTML file is opened in the browser you are now using, assuming that both class files and the HTML file are all in the same directory:


Watching for an Event

In order to make an applet interactive, Java code must be written that watches for, and responds to, events such as clicks on buttons. Take a look at The Piggy Bank Applet. If the applet appears as a gray rectangle with nothing in it, your browser is not enabled for JDK 1.1.1, and you will have to create an HTML file and use the Appletviewer to see it.

Now, let's look at the source code.


Some Hot Links

Between now and next Wednesday you might find it interesting to visit some Java-powered sites on the Web. Here are a few that I would recommend:

Last modified April 30, 1997


[Anyone Else for Java? home]