Migrating from Pascal to Java

Allen B. Tucker
August, 1997

Java is a "simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language" (The Java Language: A White Paper, Sun Microsystems, Inc).

This document provides a gentle introduction to Java if you have some Pascal (or C/C++) programming experience. It is also a work in progress, and all comments and suggestions for improving it are most welcome! Send them by e-mail to me at allen@polar.bowdoin.edu.


Contents

  1. Overall Program Structure
  2. Data Types and Variable Declarations
  3. Statements
  4. Methods (Functions and Procedures)
  5. The String Class
  6. Stream Input and Output
  7. Example: Making a Standalone Application
  8. Java Applets
  9. Colors and Other Graphics Features
  10. Buttons, Menus, and TextAreas

Java is implemented at Bowdoin on both the DEC Alphas and the Macs. More information on running Java programs on the DEC Alphas can be found in the document Using Java at Bowdoin, while information about running Java programs under CodeWarrior on the Macs can be found in the document Writing CodeWarrior Java Applications.

More complete detailed Java documentation is on line if you are logged into Arctos or Polar. Many extensive Web pages are also available on Java. A good reference book on Java is David Flanagan's Java in a Nutshell, published by O'Reilly. The example Java programs in that book have been downloaded and are available for copying and running here.


1. Overall Program Structure

A Java program is called a "class." Some Java programs are written for use in an interactive environment, while others are written as stand-alone applications. We shall discuss the structure of programs for interactive environments in a later section.

A Java program designed as a stand-alone application has a basic structure much like that of a Pascal, C, or C++ program. The program has a series of statements embedded in a method (function) called "main," a collection of auxiliary method declarations, and a collection of global variable declarations that are used by the statements in the program. The method "main" is the first to be executed when the program begins running. The syntax of a complete stand-alone Java application program is as follows:

import java.io.*;

public class <classname> {

   <variable declarations>

   <method declarations>

   public static void main (String[] args) {

     <statements to execute when the program begins running>

   }

}

The "import" statements at the beginning of the program indicate specific libraries (called "packages") which supply many useful functions, or methods, to the program. The import statement here suggests that most Java application programs use some of the stream/file input and output methods from the "java.io" package. (Java uses the term "method" as a synonym for the term "function" or "procedure," which would be a more familiar term to Pascal or C/C++ programmers.) In addition, the Java program may declare its own methods to supplement those that are provided by these libraries.

Scope of Declarations

The scope of a declaration in a Java program is the range of statements that may reference the declared variable or method. The scope of the variables and methods identified in the declarations above includes the entire program. As we shall see, all methods (including the method "main") may declare additional variables for local use, in which case their scope is limited to the body of the method in which they are declared. Variable names must be unique within the method where they are declared. Moreover, variable names are case sensitive, so that (for instance) the names "sum," "Sum," and "SUM" refer to distinct variables.

Unlike Pascal (and like C/C++), Java method declarations may not be nested. Thus, the structure of a Java program is relatively flat. When two variables have the same name, their scopes must be mutually exclusive. Thus, if a variable declared locally within a method has the same name as another variable declared among the <variable declarations>, all references to that name from within that method are treated as references to that local variable. In general, no two variables declared within a single method should have the same name.

Comments

Double slashes (//) in a Java program indicate that the rest of the line is a comment. This serves the same purpose as the braces { and } in Pascal programs.

The Standard Java Packages

The predefined Java classes are grouped into a small number of standard packages. For instance, input and output operations are performed through classes in the java.io package, which is summarized in the next section. Here's an overview of the major packages in the Java API (application programming interface):
java.applet
mainly contains the Applet class; applets are programs that run inside Web browsers.
java.awt
abstract windowing toolkit; contains classes for graphics and making GUI interfaces.
java.io
contains stream and file I/O classes. Unfortunately, Java I/O does not support automatic conversion of stream input values from their text representation to their internal numerical (int or float) representation. Thus, simple input functions in Java are a bit more tedious than their counterparts in Pascal or C/C++. This will be discussed more later.
java.lang
contains core language classes (this package is implicitly imported by all programs), like Math, String, Thread, and Throwable (for defining and handling exceptions)
java.net
contains classes for networking, including URL, Socket, DatagramSocket, and InetAddress
java.util
contains some useful general classes, like Date, Random, Vector, and Stack


2. Data Types and Variable Declarations

There are two types of variables in Java, "primitive types" and "reference types." Primitive types are passed by value when used as arguments in method calls, while reference types are passed by reference. Below are the primitive data types in Java, along with some explanations:

Primitive Type          Explanation                           Default
-------------------     ------------------------------------  -------
boolean                 true, false (not 0, 1 as in C/C++)    false
char                    Unicode character                     \u0000
byte short int long     8- 16- 32- and 64-bit signed integer  0
float double            32- and 64-bit floating point number  0.0

The "Default" values shown on the right are guaranteed to be the initial values of variables declared with each of these types.

The Unicode character set is a 16-bit representation for characters, which includes the ASCII characters. Most of these appear in a Java string as they appear on the keyboard; the following characters have escape sequences when they are typed as part of a Java string:

Character               Escape sequence
-------------------     ---------------
Backspace               \b
Horizontal tab          \t
New line                \n
Form feed               \f
Carriage return         \r
Double quote            \"
Single quote            \'
Backslash               \\

Here are some example Java variable declarations, alongside their Pascal counterparts:

Java                                    Pascal
-----------------------                 -------------------------------
float x, y;                             var x, y: real;
boolean b;                                  b: boolean;
char c;                                     c: char;
int i, j;                                   i, j: integer;

Reference types in Java are arrays and "objects." The idea of an object is similar to the idea of a variable -- an object has a state (i.e., a value) and an associated set of operations that can be performed on that value. A String variable in Java is an example of an object. A String's state is its current value (i.e., its sequence of characters between quotes), to which certain string operations (e.g., concatenation, selecting a substring, etc.), called methods, can be applied. Declaring an array or String variable in Java is somewhat more general than in Pascal, as the following examples show.

Java                                    Pascal
-----------------------                 -------------------------------
int A[] = new int[5];                   var A: array[1..5] of integer; 
float B[] = {3, 6, 9, 2};
String s = "Hello World!";              var s: string;
                                        ... s := 'Hello World';
String t;

The first line declares an array A, which in Java is indexed from 0 to 4 (not 1 to 5, as is usual in Pascal). So the reference A[0] refers to the first element in A, and A[4] refers to the last. The second line shows how in Java a declaration can initialize the values in a variable or array. The third line illustrates the declaration of a String variable in Java, along with an initial value assignment.

While standard Pascal doesn't formally support strings, most of its implementations do, as shown in the example on the right. In Java, objects are "reference types." Thus, like the array A, the String s is created as a reference to a dynamically allocated block of storage in a memory area called the "heap." If passed as an argument to a method, the array A or the String s will be passed by reference.

The default value for reference types is null. For instance, the String variable t declared above, with no initial value, is initially a null reference. Later, when the string is assigned a value, that value will be dynamically created in the heap and t will reference, or "point to," that value.

If you are beginning to suspect that Java references are something like pointers in Pascal or C/C++, you're exactly right. But you're not allowed to declare pointers in Java. Moreover, while all arrays and objects (all reference types) are dynamically allocated at run time, they never need to be explicitly deallocated by the programmer. That is, Java provides "automatic garbage collection," which prevents programs from explicitly disposing blocks of dynamic storage. In the long run, this strategy promotes more reliable and painless programming without any loss of generality. More discussion of objects, classes, and reference types appears below.


3. Statements

Java statement types include expressions (including assignments), loops, conditionals, switch, break, and continue statements. Their syntax follows their counterparts in C/C++.

Assignments

The assignment operator is = (which, by the way, should not be used as a comparison operator).

Java                                    Pascal
-----------------------                 -------------------------------
i = i + 1;                              i := i + 1;
i++;

Note that the second example is a commonly-used variation of the first. That is, the ++ operator in Java is often used to increment a variable by 1.

Other Expressions, Operators, and Mathematical Functions

Operators in Java mirror those in C/C++, except that + applies to String values (for concatenation) as well as numbers, and the dereferencing and referencing operators * and & are not available. Here is a summary of the principal Java operators, in order from highest to lowest precedence:

Java                                    Pascal
-------------------------               -------------------------------
++ -- + - ! ( <type> )                  n/a n/a + - not n/a
* / %                                   * / div mod
+ -                                     + - 
<= >= < >                               <= >= < >
== !=                                   = <> 
&&                                      and
||                                      or
= (assignment)                          :=
Note that == is the equality comparison operator in Java, not = (which is assignment). Also, note that / gives an integer quotient when both operands are integers, and a decimal quotient otherwise; so it acts sometimes like div in Pascal. Pascal's mathematical functions are available through Java's library java.lang.Math, along with some others. When using any of these, the program must have the statement
import java.lang.Math;

at its beginning, and prefix the method call by the qualifier "Math.". Here is an incomplete summary of the corresponding methods (beware of minor name changes and differences in usage):

Java                                    Pascal
-----------------------                 -------------------------------
abs atan cos exp log                    abs arctan cos exp ln
acos asin ceil floor                    n/a
max min pow random                      n/a
rint round                              n/a
n/a                                     odd ord pred succ trunc
sin sqrt tan                            sin sqrt tan

Conditionals
Java                                    Pascal
-----------------------                 -------------------------------
if ( <condition> ) {                    if <condition> then begin
   <statements>                              <statements>         
else {                                  else begin 
   <statements>                                <statements>
  }                                          end
}                                       end

The else clause is optional, as are the braces {} when the group of <statements> contains only one statement.

Loops
Java                                    Pascal
-----------------------                 -------------------------------
for (i=1; i<=n; i++) {                  for i:=1 to n do begin
   <statements>                            <statements>
}                                       end

while ( <expression> ) {                while <expression> do begin
   <statements>                            <statements>   
}                                       end
Switch and Break
Java                                    Pascal
-----------------------                 -------------------------------
switch ( <expression> ) {               case <expression> of
  case <value1>: <statement1> ;            <value1>: <statement1> ;
       break;
  case <value2>: <statement2> ;            <value2>: <statement2> ;
       break;
   ...                                     ...
}                                       end

Note that the break statement must explicitly end each of the case alternatives in the Java code if the same meaning is to be conveyed as in the Pascal version. Leaving out the break statement between two cases is sometimes useful when a different effect is needed.


4. Methods (Functions and Procedures)

A Java "method" is similar to a C/C++ function, or a Pascal function or procedure.

Java                                    Pascal
-----------------------                 -------------------------------
<type> <name> (<params>) {              function <name> (<params>) 
   <local variable declarations>            <local variable declarations>
                                          begin
   <statements>                             <statements>
   return <expression> ;                    <name> := <expression>
}                                         end;

The type returned by a method may be any primitive or reference type, or else void. A method with a void return type is comparable to a Pascal procedure. If the return type is not void, the "return" statement should be used to send the returned value to the call. As shown above, this is similar to a Pascal function, in which the result is returned by making an assignment to the function's <name>.

Remember, all parameters with primitive types are passed by value in a method call, while all parameters with reference types (arrays and objects) are passed by reference. Thus, Pascal's var parameter can always be simulated in Java by using a parameter with a reference type.

A method may be called in one of two different ways; in the conventional way or in "dot" notation. The conventional call is like an ordinary function call in Pascal or C/C++. For instance, a call to the method 'sqrt'

sqrt(x) 

returns the square root of the value of the argument x. On the other hand, the call to the method 'equals'

s.equals("Hello World!")

where s is a String, returns the boolean value true or false depending on whether the current value of s is identically "Hello World!".

A general rule of thumb for whether or not to use the "dot" notation is guided by whether or not the variable to which the method is being applied is a member of that method's class. In the above examples, for instance, the variable x has primitive type (presumably float or double), but the method 'sqrt' is a member of the Math class. Thus, the dot notation is not used. In the second example, the "dot" notation is used because the variable s is a member of the String class, and so is the method 'equals.' Invoking either the method 'sqrt' or the method 'equals' the wrong way, e.g.,

x.sqrt()
equals(s, "Hello World!")

will result in an error.


5. The String Class

Character strings are implemented in Java by way of the String class. The plus sign (+) is used to concatenate two strings into one, while the method "equals" is used instead of "==" to test for equality between two String variables or expressions. Here are a few examples of the major actions on strings.

String Action                    Example
------------------------------   -----------------------------------
Declaration                      String s;
Declaration and initialization   String s = "Hello!";
Assignment                       s = "Goodbye!";
Comparison -- equality           if (s.equals("Goodbye!)) ...
           -- less than          if (s.compareTo("Goodbye!") < 0) ...
           -- greater than       if (s.compareTo("Goodbye!") > 0) ...
Concatenation                    s = "Goodbye Cruel" + " World!";
Number of characters (length)    s.length()     returns 19 in this case
Search for a substring           s.indexOf(" ") returns the position of the
                                     first blank in s, or 7 in this case.
                                     NB the first character is at positon 0!
Substring selection              s.substring(8, 12) returns "Cruel"

While Pascal does not have a standard string type, most of its implementations support strings and a few common functions. Here is a quick summary of the differences between Java and Pascal string functions:

Java                                    Pascal
-----------------------                 -------------------------------
"Hello World!"                          'Hello World!'
String s = "Hello World!";              var s: string;
                                        ... s := 'Hello World!';
String t = "Hello " + s;                t := concat('Hello ', s);
i = t.length();                         i := length(t);
i = s.indexOf(" ");                     i := pos(s, ' ');
t = s.substring(6, 10);                 t := copy(s, 7, 5);


6. Stream Input and Output

Input and output are supported in various ways by Java. In this section, we summarize the basic facilities for reading and displaying values in the standard input and output streams, 'System.in' and 'System.out'. We then present and illustrate a simplified stream input facility developed by Duane Bailey that is easier to use than the standard fare.

The Java class 'System' has a number of predefined variables, including the following:

System.in   -- standard input stream
System.out  -- standard output stream
System.err  -- standard error log

In Unix Java applications, these streams appear in the same window that is used for compiling and running Java programs. In CodeWarrior applications, two new windows appear when running a program that uses System.in and System.out, one for each stream. This is a bit of a "kluge," since the familiar practice of seeing input typing echoed in the output window (when alternating Readln and Writeln statements in Pascal) is lost, but it is workable.

To display output in Java, either of the statements

System.out.print( <expression> );
System.out.println( <expression> );

is used, where <expression> can be any String, integer, real, or other value or expression. The second statement differs from the first only by placing a line-feed at the end of the value displayed.

To read input, a program has three options:

Here is a summary of these options.

To obtain input from the 'args' parameter in the 'main' function, that input must be listed on the same line as the run-time command for the program. For instance,

% java MyProgram.class a b c

calls for a run of the program 'MyProgram.class' by the Java interpreter, passing the values 'a' 'b' and 'c' as arguments. In turn, the program should have a 'main' method that accommodates these values, such as

public static void main (String args[])) ...

Now the String array args will have the following values for use when this program is run:

args[0] == "a"
args[1] == "b"
args[2] == "c"

The second, more flexible, option for reading input is reminiscent of Pascal or C/C++ programming, but is also somewhat tedious because the program must convert each input read to the desired type. First, a variable of type DataInputStream should be declared and initialized to point to 'System.in'.

DataInputStream MyInput = new DataInputStream(System.in);

To read a char value from the input stream, read a line of text into a String variable (called 'inputLine' below), and then extract the first character using the String method 'charAt').

try {     
     System.out.println("Enter your choice of m, d, a, p, or q: ");
     String inputLine = MyInput.readLine();
     char b = inputLine.charAt(0);
}
catch (IOException e) {
     System.out.println("I/O exeption");
}

To read an ordinary double (int, float, ...) value from the input stream, you can read a complete line of input as a String (called 'inputLine' below) and then convert it to a Double (which is the class corresponding to the simple type double, called 'dValue' below), and finally convert it to an ordinary double value using the method 'doubleValue()' before assigning it to the variable delta_x. Wow!

try { 
     System.out.println("Enter x distance to move: "); 
     String inputLine = MyInput.readLine(); 
     Double dValue = new Double(inputLine); 
     double delta_x = dValue.doubleValue(); 
}
catch (IOException e) { 
    System.out.println("I/O exeption"); } 
catch (NumberFormatException e) { 
    System.out.println("Invalid number entered");
} 

The third option for reading input is similar to Pascal or C/C++ stream input. To use it, you must use the nonstandard class ReadStream (which was developed by Duane Bailey at Williams College). If you are running CodeWarrior Java, you must also add the following import statement at the beginning of the program, in order to get an input stream window opened at run time:

import com.mw.io.*;

When running CodeWarrior Java, you must also have a statement at the beginning of your main method that opens this input window:

SystemInput sysIn = new SystemInput(); // open the input window

To close this input window, use the following statement at the end of your main method:

sysIn.dispose();

To gain access to the stream input methods of the class Readstream, you must first declare a ReadStream variable, say r, using the following syntax:

try {
      ReadStream r = new ReadStream();       // create an input stream
      <statements> 
} 
catch (Exception e) {
      System.out.println("Exception " + e.toString() + " occurred");
}

This is the normal form of an input operation in Java, which treats an input operation as one which might raise an "exception." That is, if the program is looking for an integer and the user types the character "a" then an exception will be raised. This code will "catch" that exception when it occurs and display a message before resuming the program.

Now the <statements> that can be used inside this input operation will be input statements of the form

<variable> = r.<method>();

where <method> is chosen from the following list in accordance with the type of the <variable> on the left.

String readString()
    // reads next word as string
String readLine()
    // reads remainder of line, returns as string
boolean readBoolean()
    // returns next boolean value read from input
char readChar()
    // returns next character, or 0 for eof
double readDouble()
    // reads in double value
float readFloat()
    // reads floating point value and returns value
short readShort()
    // reads a short integer from stream
int readInt()
    // reads an integer from stream
long readLong()
    // reads a long integer from stream

For instance, to read the next line from the input stream r and assign it to the String variable s, you would use a statement of the form:

s = r.readLine();

This corresponds to the Pascal statement readln(s), where the conversion of the input to a string value and assignment to the variable s is implicit.

The following additional methods are available in the ReadStream class:

boolean eof()
    // are we at the end-of-file?
boolean eoln()
    // returns true if next stream char is a eoln char
void readln()
    // reads input stream until end-of-line (\r or \n)
void skipWhite()
    // input pointer is at EOF, or non-whitespace (not blank, \r, \n, or \t) char.

The eof and eoln methods correspond to functions with the same name in Pascal, while the readln method corresponds to the use of readln in Pascal with no arguments (a device to skip to the beginning of the next input line).

The method eof will return true when the user enters command-D on the keyboard (in a CodeWarrior Java environment) or ctrl-D on the keyboard (in other environments).


7. Example: Making a Standalone Application

Here is a stand-alone Java program that will input a number and display a countdown from that number to 1 followed by the message "Welcome to Java!" It is set up to run under CodeWarrior Java because of the import statement on the second line and the lines inside the program that open and close the input window. These lines would not be needed in non- CodeWarrior Java environments.

import java.io.*;
import com.mw.io.*;

public class MyFirst {      
        public static void main(String args[]) {
            SystemInput sysIn = new SystemInput(); // open the input window   
         try {
            ReadStream r = new ReadStream();       // create an input stream
            int n = 0;
            System.out.println( "Enter an integer in the System.in window");
            n = r.readInt();                       // read an input integer
            for (int i=n; i>0; i--)
              System.out.println(i);
            System.out.println( "Welcome to Java!" );
            sysIn.dispose();                       // close the input window
         } 
         catch (Exception e) {
            System.out.println("Exception " + e.toString() + " occurred");
            sysIn.dispose();
         }
        }

}

Note that the int variable n is declared at the point where it is first used, inside the input statement. We could have declared and initialized n outside the main method altogether, in which case it would be globally accessible to all methods inside the program (if there were others). Notice also that output of different types of values is achieved easily by concatenating several strings together inside a System.out.println statement. This is a very handy feature of Java.

A roughly equivalent Pascal program for this problem is shown below, so that other correspondences and differences between Java and Pascal can be identified.

program myfirst (input, output);

var i, n: integer;

begin
        n := 0;
        writeln('Enter an integer:');
        readln(n);                       { read an input integer}
        for i := n downto 1 do
           writeln(i);
        writeln('Welcome to Pascal!');
end.


8. Java Applets

This section provides a brief introduction to the basic concerns of programming for human-computer interaction, or HCI. Java programs designed for interactive use are called "applets." When it is running, an applet appears as a rectangular graphical area inside a Web browser and can handle a variety of "events" (mouse clicks, menu selections, button clicks, line drawings, etc.) that are initiated by the user. When a Java program is written in this way, it often has the following general structure:

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

public class <classname> extends Applet {

   <variable declarations>

   <method declarations>

   public void init() {

     <code to initialize the applet when the program begins executing>

   }

   <event handlers; these respond to events initiated by the user>

}

The following Java program is adapted from the book Java in a Nutshell by David Flanagan (Copyright (c) 1996 O'Reilly & Associates).

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

public class Lab8 extends Applet {
    private int last_x = 0;
    private int last_y = 0;
    private Color current_color = Color.black;
    private Button clear_button;
    
    // This method is called initially, when the program begins
    // executing.  It initializes the graphics window.
    public void init() {
        // Set the background color
        this.setBackground(Color.white);

        // Create a button and add it to the graphics window
        clear_button = new Button("Clear");
        clear_button.setForeground(Color.black);
        clear_button.setBackground(Color.lightGray);
        this.add(clear_button);
    }
    
    // Called when the user clicks the mouse to start a scribble
    // Sets the values of variables last_x and last_y to mark the
    // point of the click.
    public boolean mouseDown(Event e, int x, int y)
    {
        last_x = x; last_y = y;
        return true;
    }
    
    // Called when the user scribbles with the mouse button down
    // Draws a line between the points (last_x, last_y) and (x, y)
    public boolean mouseDrag(Event e, int x, int y)
    {
        Graphics g = this.getGraphics();
        g.drawLine(last_x, last_y, x, y);
        last_x = x;
        last_y = y;
        return true;
    }

    // Called when the user clicks the Clear button, and 
    // clears the graphics window.
    public boolean action(Event event, Object arg) {
        // If the Clear button was clicked, clear the graphics window
        if (event.target == clear_button) {
            Graphics g = this.getGraphics();
            Rectangle r = this.bounds();
            g.setColor(this.getBackground());
            g.fillRect(r.x, r.y, r.width, r.height);
            return true;
        }
        // Otherwise, let the superclass handle it.
        else return super.action(event, arg);
    }

}

The above program has three specific event handlers, one to respond to the user pressing the mouse button, one to respond to the user dragging the mouse after the button is depressed, and one to respond to the user clicking the the "Clear" button on the screen.


9. Colors and Other Graphics Features

Colors and graphics methods are features in Java that are not well- supported in Pascal. Specifically, Color is a distinct class in Java, and we can declare variables of class Color. For instance:

Color C = new Color(Color.green);

declares the variable C to have color green, which is one of the "constants" available for class Color (just like 1, 2, 3, etc. are the constants available for the type integer in Pascal).

We can also declare an array of colors and initialize it with four different color constants, as follows:

Colors A[] = {Color.green, Color.red, Color.blue, Color.yellow};

Now A[0]==Color.green, A[1]==Color.red, and so forth.

The following two commands can be used to set the foreground and background colors of the current applet. These settings affect the color of lines and text drawn in the applet.

this.setForeground( <color> );   // sets the foreground of the applet to 
                                 // "color," which is normally Color.black
this.setBackground( <color> );   // sets the background of the applet to 
                                 // "color," which is normally
Color.white

The graphical drawing environment of the current applet can be obtained by the following declarations and assignments:

Graphics g = this.getGraphics();
Rectangle r = this.bounds;

This declares the variable g as type Graphics and initializes its value to the window where the current Java applet is running. The rectangle r is a variable that has four fields -- r.x, r.y, r.width, and r.height -- which are assigned the values 0, 0, 500, and 300 (assuming that the width and height of the applet in which the program is running are 500 and 300). This variable g, since it is of type Graphics, has the following features and available methods (functions):

g.setColor( <color> );        // sets the current "color" for 
                                  //   and filling shapes in the graphics area
g.fillRect(x, y, width, height);  // fills the rectangular area with upper-left
                                  //   corner location (x, y), width, and height
                                  //   all specified in integer pixels.
g.drawRect(x, y, width, height);  //   draws the outline of that rectangle
                                  //   note: a square is a special kind of rect.
g.fillOval(x, y, width, height);  // fills the oval defined by that rectangle
g.drawOval(x, y, width, height);  //   draws the outline of that oval
                                  //   note: a circle is a special kind of oval
g.drawLine(x, y, z, w);           // draws a straight line from (x, y) to (z, w)
g.drawString(s, x, y);            // displays the String s, starting at (x, y)


10. Buttons, Menus, and TextAreas

Different kinds of objects can be placed in an applet to facilitate user interaction. Already we know how to handle mouse clicks and draw lines on the screen. This section discusses the use of Buttons, Choices (these are like Menus), TextAreas, and TextFields -- how they are declared, how they are initialized and placed inside an applet, and how user selections of these objects are handled by event-handlers.

Buttons

Declaration: A button is an object on the screen which is named and which can be selected by a user mouse click. Any number of variables can be declared of class Button and placed in the applet. A button is declared as follows:
General form                          Example
----------------------------------    ----------------------------------
Button <variable> ;                   Button clear_button;
Initialization and placement: The button is named and placed in the applet as part of the init method in your program.
General form                          Example
----------------------------------    ----------------------------------
<variable> = new Button("<name>");    clear_button
= new Button("Clear");
Event-handling: When the user selects the button, your program can handle that event by writing the following method:
General form                         
------------------------------------------------- 
public boolean action(Event event, Object arg) {
   if (event.target == <variable>) {
     <action>
     return true;
   }
}

Here, the <variable> refers to the name of the Button variable as declared and initialized, like "clear_button" in the example above. When the event occurs, the <action> specified in this handler is executed. The statment return true; signals that the event has been completely handled.

Choices (Menus)

Declaration: A choice is an object on the screen which is named and which offers several options to be chosen by a user. Any number of variables can be declared of class Choice and placed in the applet. A choice is declared as follows:
General form                          Example
----------------------------------    ----------------------------------
Choice <variable> ;                   Choice user_choice;
Initialization and placement: The choice is named and placed in the applet as part of the init method in your program. The different choices are assigned to the Choice variable using the addItem method
General form                          Example
----------------------------------    ----------------------------------
<variable> = new Choice();            user_choice = new Button();
<variable>.addItem(<string1>);       
user_choice.addItem("North");
<variable>.addItem(<string2>);       
user_choice.addItem("East");
...                                   user_choice.addItem("South");
this.add(<variable>);                
user_choice.additem("West");
                                      this.add(user_choice);
Event-handling: When the user selects the choice, your program can handle that event by adding the following code to the "action" method:
General form                         
------------------------------------------------- 
public boolean action(Event event, Object arg) {
   String s = (String) arg;
   if (event.target == <variable>) {
     <action, using the string value "s" of the choice selected>
     return true;
   }
}

Here, the <variable> refers to the name of the Choice variable as declared and initialized, like "user_choices" in the example above. When the event occurs, the <action> specified in this handler is executed. The String s has the value of the choice the user selected, which is passed to the handler by way of the parameter "arg". Thus, in the <action> part we might write code such as:

if (s.equals("North")) ...
else if (s.equals("East")) ...

to discriminate among the selections the user has made. The statement "return true;" again signals that the choice selection event has been completely handled.

TextAreas and TextFields

Declaration: A TextArea is an object on the screen which is named and can display text messages to the user. It is a scrollable object, so users have a complete record of the text output. A TextField is an object into which the user can type a single line of text from the keyboard; it raises an event when the user types the return key at the end of the line. TextAreas and TextFields are declared as follows:
General form                          Example
----------------------------------    ----------------------------------
TextArea <variable> ;                   TextArea echo_area;
TextField <variable> ;                  TextField user_typing;
Initialization and placement: TextArea and TextField objects are named and placed in the applet as part of the init method in your program. Initialization requires the number of lines of text (for TextAreas) and the number of characters per line.
General form                          Example
----------------------------------    ----------------------------------
<variable1> = new TextArea(<lines>, <chars>); 
                                       echo_area = new TextArea(5, 40);
<variable1>.setEditable(false);        echo_area.setEditable(false);
this.add(<variable1>);                 this.add(echo_area);

<variable2> = new TextField(<chars>);  user_typing = new TextField(40);
this.add(<variable2>);                 this.add(user_typing);

In these examples, we have declared and placed a 5 x 40 TextArea and made it unwriteable by the user. We have also declared and placed a 40- character writeable TextField in the current applet.

Event-handling: When the user types in the TextField and hits the return key, your program can handle that event by writing additional code in the "action" event handler:
General form                         
------------------------------------------------- 
public boolean action(Event event, Object arg) {
   String s = (String) arg;
   if (event.target == <variable>) {
     <action, using the user's typed text, which is stored in s>
     return true;
   }
}

Here, the <variable> refers to the name of the TextArea variable as declared and initialized, like "user_typing" in the example above. When the event occurs, the <action> specified in this handler is executed. The statement "return true;" signals that the event has been completely handled.

The user's typing can be echoed in the TextArea by concatenating it with all the text that's already there. The getText and setText methods are useful in either of the following equivalent ways:

    echo_area.setText(echo_area.getText() + s + "\n");
    echo_area.appendText(s + "\n");

If this line is added before the 'return true;' statement in the above code, the user's typing will be echoed on a new line inside the TextArea object named 'echo_area'.