CS 4773 Object Oriented Systems


The Java Language (continued)

The examples Test1.java through Test12.java are available in /usr/local/courses/cs4773/spring97/examples/set01


Classes

When the following is compiled, two files are created:
Test11.class and Point.class.

Note the two constructors for the class Point.

class Point {
   protected double x;
   protected double y;
   Point (double x, double y) {
      this.x = x;
      this.y = y;
   }
   Point () {
      x = 0;
      y = -1;
   }
   public void show () {
      System.out.println("("+x+","+y+")");
   }
}

class Test11 {
   public static void main(String args[]) {
      Point p1;
      Point p2;
      p1 = new Point(3.5, 4.7);
      p1.show();
      p2 = new Point();
      p2.show();
   }
}

java Test11
(3.5,4.7)
(0,-1)
The class Point3D extends the class Point.

The import statement reads in the Point.class file so that the Point class is known.

Note that there are no header files used.

import Point;

class Point3D extends Point {
   protected double z;
   Point3D(double x, double y, double z) {
      this.x = x;
      this.y = y;
      this.z = z;
   }
   public void show() {
      System.out.println("("+x+","+y+","+z+")");
   }
}

class Test12 {
   public static void main(String args[]) {
      Point3D p1;
      p1 = new Point3D(3.5, 4.7,9.4);
      p1.show();
   }
}

java Test12
(3.5,4.7,9.4)

Exceptions

In C, a fatal error can cause a core dump.

This cannot happen in Java.

In C under Unix, system errors are handled using errno.

Java handles these with exceptions.

A method which can cause an exception either handles it itself or can throw the exception to the calling method.

Examples of exceptions:

Methods that can throw an exception should be wrapped in a try --- catch

try {
   c = a/b;
} catch(ArithmeticException e) {
   System.out.println("Divide by 0");
}

Packages, Classes, Interfaces, Methods, Fields, and Objects

An object groups data and code.

The code in an object is made up of methods.

The data is contained in fields.

A class is a description of the methods and fields of a collection of objects.

A constructor is a special method in a class which is used to initialize an object when the object is created.

An interface contains constants and method prototypes.

A class can extend another class and implement any number of interfaces.

A package is a collection of classes.


Packages and Name Space Resolution

Packages allow a collection of classes to grouped together.


Applets

Applets are programs meant to be run by a browser.

Applets and applications have a different structure.

An application has a public method called main which is started by the interpreter when the program is loaded. An applet is a public class which extends the Applet class. It usually has a method called paint which displays something on the screen. Here is an example of an applet:

import java.awt.*;
import java.applet.*;
public class HelloWorldApplet extends Applet {
   public void paint(Graphics g) {
      g.drawString("Hello World!", 20, 20);
   }
}
This writes the string ``Hello World!'' on the screen starting at position with (x,y) coordinates (20,20).

(0,0) is in the upper left corner.


Testing Applets

The appletviewer is used to run applets.

You pass to the appletviewer the name of an HTML file which has the tag applet and the name of a file containing the compiled class.

< applet code="HelloWorldApplet" width=200 height = 40 >
< /applet >
This displays the applet in a box 200 pixels wide and 40 pixels high.

In fact, for testing, it is convenient to put both the source of the applet and the HTML in the same file.

The HTML code is put inside a comment so that it is ignored by the Java compiler.

The appletviewer ignores anything not in the scope of the applet tag.

Put the following in a file called HelloWorldApplet.java

/*
 * < applet code="HelloWorldApplet" width=200 height = 40 >
 * < /applet >
*/
import java.awt.*;
import java.applet.*;
public class HelloWorldApplet extends Applet {
   public void paint(Graphics g) {
      g.drawString("Hello World!", 20, 20);
   }
}


To compile:
javac HelloWorldApplet.java

To run:
appletviewer HelloWorldApplet.java

This produces the following:

Click Here to run this applet.


The Applet Tag

< APPLET
   [CODEBASE = codebaseURL]
    CODE = appletClassFile 
   [ALT = alternateText] 
   [NAME = appletInstanceName]
    WIDTH = pixels
    HEIGHT = pixels
   [ALIGN = alignment]
   [VSPACE = pixels]
   [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue > ] 
[< PARAM NAME = AttributeName VALUE = AttributeValue > ] 
...
[HTML displayed in the absence of Java]
< /APPLET >
The required fields are: Some of the optional fields are:

Passing Parameters to Applets

The following is HTML code which starts an applet and passes 2 parameters.
/*
 * < applet code="animation_test.T1" width=200 height = 100 >
 * < PARAM NAME = fontsize VALUE = 30 >
 * < PARAM NAME = message VALUE = hello >
 * < /applet >
*/
The values are passed to the Java code as strings and so they may have to be converted.

The following Java code might be used for this example:

Times_Fontsize = 
   Integer.parseInt(getParameter("fontsize"));
Times_String = getParameter("message");
Use Float.ValueOf() to convert a String to float.

The above examples leave out the error checking.


Applet Initialization

void init() is called first.
Use this to initialize your variables.

void start() is called after init.
It is called each time the applet's HTML document is displayed on the screen, for example if a browser revisits a page.

void paint(Graphics g) is called by the AWT when it thinks it is necessary, say when an applet is uncovered.

void update(Graphics g) is called by the AWT when you call repaint()
You should probably override is since if first fills the applet with the default background color causing the screen to flash.

void stop() is called when the browser leaves the page containing the applet's HTML.
Use this to suspend your threads and restart them with start().

void destroy() is called when your applet needs to be removed from memory. This should free up your resources.


Repainting

The paint(Graphics g) method is used by the AWT to repaint the applet when it thinks it is necessary.

This should redraw the entire applet.

The update(Graphics g) is (eventually) called in response to a call to repaint().

Several calls to repaint may result in a single call to update.

A call to repaint(long time) is a request to call update within time milliseconds.

It may not be honored if the system is busy.

Why not call paint yourself?

You do not have the g to pass to it.


The Graphics Context

The Graphics class is part of java.awt.

A Graphics object cannot be created with new.

It can only be created from another graphics object.

Graphics newGC;
Graphics currentGC;
Image current_image;

/* Crate an image of size 100 by 100 */
current_image = createImage(100,100);

/* Create a graphics context */
currentGC = current_image.getGraphics();
/* Set this one to draw in green */
currentGC.setColor(Color.green);

/* Create another one from the first */
newGC = currentGC.create();
/* Set this one to draw in light red */
newGC.setColor(new Color(255,200,200));

Some Graphics Methods

void drawRect(int left_x, int top_y, int width, int height)

void fillRect(int left_x, int top_y, int width, int height)

void drawOval(int x, int y, int width, int height)

void fillOval(int x, int y, int width, int height)

void drawArc(int x, int y, int width, int height,
            int startAngle, int arcAngle)

void fillArc(int x, int y, int width, int height,
            int startAngle, int arcAngle)

void drawLine(int x1, int y1, int x2, int y2)

void drawPolygon(int xPoints[], int yPoints[], int nPoints)

void fillPolygon(int xPoints[], int yPoints[], int nPoints)

Writing Text

Choosing a font:
/* 12 point Courier bold font */
myGC1.setFont(new Font("Courier",Font.BOLD,12));

/* 20 point Times font */
myGC2.setFont(new Font("Times",Font.PLAIN,20));
To write text use

void drawString(String str, int x, int y)

myGC1.drawString("Hi there",10,20);
myGC2.drawString("Hi there",10,60);
Information about the size of a string in a font can be obtained using FontMetrics
FontMetrics fm;

fm = getFontMetrics(myGC1.getFont());
ascent = fm.getMaxAscent();
descent = fm.getDescent();
width = fm.stringWidth("How are you");