Week 10 - March 23, 1999

Classes and objects
The structure of a Java applet
GUI: User Controls
An Example

Classes and objects

A class is a collection of data and methods that operate on that data. The data and methods, takend together, usually serve to define the concepts and capabilities of some kind of object.

Let's look at the following example. We will deinfe a complex number class.

public class Complex {
}

Now, let's define the following applet

import java.applet.*;
import java.awt.*;
public class testComplex extends Applet {
    public void paint(Graphics g) {
        g.drawString("Test Complex class!",10,15);
        Complex c1 = new Complex (3,4);    // set c1 to be 3+4i
        Complex c2 = new Complex ();    // set c2 to be 4-3i
        c2.a=4;
        c2.b=-3;
        g.drawString("c1 = "+c1.toString(),10,30);
        g.drawString("c2 = "+c2.toString(),10,45);
        g.drawString("conjugate of c1 = "+c1.conjugate().toString(),10,60);
        g.drawString("conjugate of c2 = "+c2.conjugate().toString(),10,75);
        g.drawString("abs(c1) = "+Double.toString(c1.Abs()),10,90);
        g.drawString("abs(c2) = "+Double.toString(c2.Abs()),10,105);
        g.drawString("c1*c2 = "+c1.multiply(c2).toString(),10,120);
    }
}

Let's take a look and see the output of this Java applet. In the example above, Complex is a class and c1 and c2 are reference variables that point to two objects created using the class Complex and the new keyword. This way, we have created instances of our Complex class and have assigned them to the variables c1 and c2, which are of type Complex.

The structure of a Java applet

The minimal structure of a Java applet looks like the code in the following example.

import java.applet.*;
import java.awt.*;

public class MyApplet extends Applet {

}

There are three main methods that we have to define inside a Java applet: init(), paint(), and handleEvent(). We will discuss each of them individually. All these methods have to be declared public since they are called automatically by the Java Virtual Machine. In general, the user never calls directly these methods.

public void init()

This method is called by JVM every time the applet is started. In this part of the program we will put all the initialization code: computing variables, initializing the GUI (graphic user interface) by adding buttons and other controls, setting the arrays, etc. You can not draw anything here for the GUI since the Graphics context of the applet is not yet created. Put all the graphic part of the GUI in the paint method.

public void paint(Graphics g)

This method is called by JVM each time it has to redraw the screen (either if we just started the applet and we have to draw the screen for the first time or there was another window that obstructed the applet until now). We don't have to redraw any of the controls (buttons, scrollbars, text fields, etc) since they are updated automatically by the JVM. All we have to redraw is the stuff we created using methods from the Graphics class (like drawOval, drawLine, etc). When this methid is called by the JVM, the relative data variable g is set to point to the Graphics context of our applet, so all we have to do is redraw our interface using g.

Note: All what you have drawn using the Graphics class methods will be lost if you applet is partially or total covered by another windows. We will learn later about different methods we can use to avoid this problem. If the data you are drawing can be recomputed (for example, you are drawnig a function), then it is easy to recreate this in the paint() method.

public boolean handleEvent(Event event)

This method will receive and proicess all the events regarding this applet. An event is an action that the user did when interacting with the computer: moved the mouse, clicked the mouse buttons, pressed a key, selected a menu option, pressed a button in the GUI. Event are packed in a data structure that, together with a set of methods, form the Event class. In this method we have to analyze what kind of event had happened and to perform the tasks we associated with that control (button, scrollbar, etc) or action (clicking, dragging or releasing the mouse, etc). We will study event and the Events class in detail later in this course. The handleEvent() method returns true if it processed the event internatlly or false if there was an error. The method will call the handleEvent() method of the next hierarchically class if the action does not meet any of our conditions. (this is done by calling super.handleEvent() method).

Note: One can process some particular types of events outside the handleEvent() method, using other standard methods: mouseDown(), mouseUp(), mouseDrag(), action()etc. It is recommended to write all the action handeling command inside the handleEvent() method, for future compatibility with the new releases of Java and also for a better code understanding.

GUI: User Controls

In this section we will talk about the user controls we can use to define the GUI. These controls are Button, List, Choice, Checkbox and CheckboxGroup, TextField and TextArea, and Scrollbars.  We will try to touch each of these classes so you will get the basics. For examples look at the example following these notes and at the advanced examples in the book.

Button

Use to define a button. The Button generates an ACTION_EVENT event, with the button label as its argument. To create it, use the class constructor:

Button ok_button = new Button("OK");

You can set/change the text of a button later using the setLabel() method:

ok_button.setLabel("Okay");

List

The list control allows the user to choose one or more elements from the list. To create this control, we use the class constructor and another method. First we create the instance, then we add the elements we want to be listed. When the user double-clicks on an item, a List generates an ACTION_EVENT event. When an element is selected (simple-click), the List generates and LIST_SELECT event, and when an element is deselected, it generates a LIST_DESELECT event. In both cases, the event argument is the label of the affected item in the List.

List myList = new List(3,true);
myList.addItem("Perl");
myList.addItem("C++");
myList.addItem("Java");

The two arguments used in the constructor represent the number of visible rows and the option for multiple selectrion (true or false).

Choice

This class creates a menu of options that drops down from a button. To create it we call the class constructor (no arguments in this case) and then we use the addItem method, as we did for List. This class generates an ACTION_EVENT event with the label of the selected item as its argument.

Choice myChoice = new Choice;
myChoice.addItem("Red");
myChoice.addItem("Blue");

Checkbox and ChechboxGroup

These two classes create a set of options, each of them has two states: On (true) or Off (false). If we group them in a CheckboxGroup, we will obtain mutual exclusion, also known as "radio buttons". To create just a Checkbox, allowing the user to select or not a given option, we use the simple class constructor:

Checkbox simpleCB = new Checkbox("Include file name?");

You can check the state of a button by using the getState method that return true or false if the box is checked or not.
To group multiple checkboxes and create a set of radio buttons, we have first to declare the CheckboxGroup variable that will create the mutual exclusion. The we will use a different class constructor for Checkbox, one that will have as arguments the name of the box, the CheckboxGroup  variable and the initial state (true or false).

CheckboxGroup myGrp = new CheckboxGroup();
Checkbox firstElem = new Checkbox("All",myGrp,true);
Checkbox secondElem = new Checkbox("Even", myGrp,false);
Checkbox thirdElem = new Checkbox("Odd",myGrp,false);

When a Checkbox is selected, it generates an ACTION_EVENT event.

TextField and TextArea

These two classes create components that allow users to view and edit a line (TextField) or multiple lines (TextArea) of text. When you use the constructor, you can set the number or columns (for both classes) and rows (for TextArea) and the original text. Later, you can obtain the text or set a new one using the methods getText and setText.

Scrollbar

This class generates a scrollbar that the user can use to set a give value. When we create an instance of this class using the class constructor, we will pass a number of parameters that will define the orientaton (VERTICAL or HORIZONTAL), original value, minimal value, and maximal values. This class generates one of the following events: SCROLL_LINE_UP, SCROLL_LINE_DOWN, SCROLL_PAGE_UP, SCROLL_PAGE_DOWN, or SCROLL_ABSOLUTE.

An Example

Let's take a look at the following example and try to understand the code.