Programmer Exam Topics

index

acme rocket home

java skinny

certification topics

certification example

resources

books

web development

bookshelf

projects

clients

about

[ frames | no frames ]

Topic 1: Write constructor bodies using this () and super () to access overloaded or overridden constructors in the current or a parent class.

Constructors in the super class can be called using super(), called with parameters matching those in the super class. Constructors in the same class can be called using this(), called with parameters matching those in the class method. This allows constructors to be chained within the class.

public class SuperClass {
	public SuperClass() {
		// Do some init stuff
	}
	
	public SuperClass( String str ) {
		// Calls SuperClass() to do some init stuff
		this();
 
		// Do more init stuff
	}
}
 
public class SubClass extends SuperClass {
	public SubClass() {
		// Initialize first with the superclass.
		super();
 
		// Do some subclass init stuff
	}
		
	public SubClass( int num ) {
		// Call SuperClass( String ) to do init stuff
		super( "i = " + String.valueOf( num ));
	}
}


Topic 2: Employ variables, constructors, and methods for a class, using documentation written in standard "Javadoc" format and documentation inherited from a superclass.

Refer to the java.lang.Math API docs to see the standard look of Javadoc generated documentation. ### On-line xref to javadoc formatting info


Topic 3: Distinguish between overloaded and overridden methods. Identify legal return types for an overloaded method. Identify legal return types for an overridden method.

Method overloading is done by defining more than one method with the same name but with a different parameter list. Any type my be returned, as only the name of the method and the number and types of parameters are considered for overloading. Overloading is determined at compile time. In the following example, method() is overloaded.

class Overload {
	public void method() {
		// No parameters, returns void
	}
	
	public int method( int a, int b) {
		// Two parameters, returns an int
	}
	
	public void method( String[] c ) {
		// One parameter, returns void
	}
}

Method overriding is done by defining a method in the class with the exact same signature (same method name, and parameters) and return type as a method in the super class. The return type must match or the super class method will not be overridden. The runtime environment will determine at runtime which method should be called.

class Override extends Overridden {
	public void method( int a, int b ) {
		// This method overrides Overridden.method()
	}
	
}
 
class Overridden {
	public void method( int a, int b ) {
	}
}

Overridden methods may throw only the exceptions that the method that they override throws. This includes subclasses of the thrown exception. See ### for more details.


Topic 4: Employ object oriented relationships specified using the clauses 'is a' and 'has a'.

The 'is a' relationship implies inheritance, which is denoted with extends in Java. For example:

public class Car {
}
 
public class Ford extends Car {
}

In this situation, we say a Ford is a Car, and inherits many of the attributes and methods that a Car may have.

The 'has a' relationship implies containment, that the containing class is made up of several other classes. For example:

public class Wheel {
}
 
public class Car {
    Wheel[] wheels = new Wheel[4];
}

In this case, we would say that a Car has 4 Wheels. (You could say has a, but it wouldn't read as cleanly.)


Topic 5: Distinguish legal and illegal orderings of the following top-level Java source file elements: package declarations, import statements, public class declarations, and non-public class declarations.

The standard way to define elements in a Java source code file is:

package com.acmerocket.util;
 
import java.util.*;
import java.net.*;
 
public class ThePublicClass {
}
 
class AHelperClass {
}
 
class AnotherHelperClass {
}

The package must be defined first, then the imports, then classes. Classes can be defined in any order, but there can only be one public class in the file, and the file must be named after the public class (i. e. the above code would be in a file calles ThePublicClass.java.) These restrictions are enforced by the compiler.

Note: It has been said that only one public class may be defined in a Java source file, and that the file must be named after that class. This is a restriction of the JDK (and many other development tools), not of the Java language.


Topic 6: Demonstrate the use of fields of the class java.awt.Event and identify the affected component, mouse position, and nature and time of the event.

From java.awt.Event API documentation:

id
public int id
The type of the event.

key
public int key

The key that was pressed in a keyboard event.

modifiers
public int modifiers

The state of the modifier keys.

target
public Object target

The target component. This indicates the component over which the event occurred or with which the event is associated.

when
public long when

The time stamp of the event.

x
public int x

The x coordinate of the event.

y
public int y

The y coordinate of the event.

Some example code:

import java.util.Date;
 
public boolean handleEvent( Event event ) {
    // Check to see if it was a mouse down event
    if ( event.id == Event.MOUSE_DOWN ) {
        // Check what the target object is
        Object clickedOn = event.target;
 
        // Get the coordinates of the event
        int mouseX = event.x;
        int mouseY = event.y;
 
        // Figure out which mouse button was down
        if ( event.modifiers && Event.META_MASK ) {
            // Right mouse button is down
        }
        else if ( event.modifiers && Event.ALT_MASK ) {
            // Middle mouse button is down
        }
        else {
            // Left mouse button is down
        }
 
        // Get the event time;
        Date clickTime = new Date( event.when );
 
 
        // Finally, return true to signify that the
        // event has been handled
        return true;
    }
    // return false, the event has not been handled
    return false;
}


Topic 7: Describe the correct destination for a main () method. Select specific command line elements from the arguments of the main method using the correct array subscript value.

A main() method can be defined for any public class and that main() will be called when the Java runtime environment is executed with that class as a parameter. The defination of main must have a specific signature:

public static void main( String[] args ) {}

public is needed to make the method visible external to the package, static is needed to make the method a class method, main() itself returns no void and the String array is needed to capture the arguments to main().

The arguments are passed to main() as items in an array of Strings, and can be accessed by looping through that array:

	public static void main( String[] args ) {
		// Print args
		for ( int i = 0; i < args.length; i++ ) {
			System.out.println( "args[" + i + "] = " 
                                      + args[i] );
		}
	}

The above example will simply print the arguments to standard out.

Some other notes about main(): main() is a static (class) method, so it cannot access the instance variables of the class it is defined in. Further, as it is a static method, it cannot access this.


Topic 8: Declare variables of type "array of X", given a type of X. Identify the legal positions for the "{}" part of an array declaration. Construct literal char values using quoted formats. Construct literal char values using the unicode escape format of Java.

Arrays in Java are typically written as

String[] strings = new String[10]; 
String strings[] = new String[10]; // exactly the same

or

String[] strings = { "This", "is", "a", "test." };

Multidimensional arrays can be initialized as well:

int[][] = {{ 1, 2, 3 }, { 10, 9, 8 }};

A char array can be created with:

char[] charArray = {'a','r','r','a','y',' ','o','f',
                    ' ','c','h','a','r'};

but this is not a String. Individual chars can be assigned with:

char one = 'a';
char two = '\u0010'; // unicode assignment


Topic 9: Identify all Java keywords from a list of keywords and non-keywords.

The following are reserved keywords in Java:

abstract

default

goto

null

synchronized

boolean

do

if

package

this

break

double

implements

private

throw

byte

else

import

protected

throws

case

extends

instanceof

public

transient

catch

false

int

return

true

char

final

interface

short

try

class

finally

long

static

void

const

float

native

super

volatile

continue

for

new

switch

while

This list is from the Java Language Specification, section 3.9.


Topic 10: Define the range of primitive data types byte, short, int, long, and char.

byte

8 bits

-128 to 127

short

16 bits

-32768 to 32767

int

32 bits

-2147483648 to 2147483647

long

64 bits

-9223372036854775808 to 9223372036854775807

char

16 bits

'\u0000' to '\uffff'

This list is from the Java in a Nutshell book.


Topic 11: Demonstrate the use of methods of the java.lang.Math class in an assignment expression: abs(), ceil(), floor(), max(), min(), random(), round(), sin(), cos(), tan(), sqrt().

Refer to the java.lang.Math API docs for detailed information about these methods.


Topic 12: Determine the value of a member variable of any type when no explicit assignment has been made to it. Determine the value of an element of an array of any base type, when the array has been constructed but no explicit assignment has been made to the element. (Knowledge of requirement for definite initializztion before use of method automatic variables required.)

All member variables and array values in Java are initialized to a default value. For all numbers, it is 0. Boolean values initialize to false. Strings initialize to "" (the empty string). Chars initialize to '\u0000'. Objects initialize to null. Values in arrays initialize to their default values.

boolean a = false;
byte b = 0
short c = 0;
int d = 0;
long e = 0;
float f = 0.0;
double g = 0.0;
char h = '\u0000';
Object i = null;
Object[] j = { null, null, null };

On the other hand, automatic (local) variables must be initialized before they can be used. The compiler will error on any automatics that are not initialized.


Topic 13: Deterine the result, in terms of a bit pattern, of applying the >> and the << operators to an integer value specified as a bit pattern. Determine the result, in terms of a bit pattern, of applying the >>> operator to an integer value specified as a bit pattern.

<< shifts the bits left

>> shifts the bits right, filling with the leftmost bit

>>> shifts the bits right, filling with 0. This will force the number to be positive.

For example, for the for the following bit pattern:

x        = 10001010
x << 3   = 01010000
x >> 3   = 11110001
x >>> 3  = 00010001


Topic 14: Determine at run time if an object is an instance of a specified class or some subclass of that class using the instanceof operator.

if ( aThingy instanceof java.util.Vector ) {
    aThingy.addElement( "new item" );
}


Topic 15: Recognize the implications of the immutability rule of the String class.

You can't alter the contents of a String. All String methods return a new String. To alter the contents of a string, you must use a StringBuffer object.


Topic 16: Determine the result of the + operator applied to a combination of variables or constants of any type.

+ is used for math operations on simple types.

+ is also overloaded do String concatination.

+= is also overloaded for String, to do concatination.


Topic 17: Determine the result of applying the == comparison operator to any two objects of any type. Determine the result of applying the equals () method to any combination of objects of the classes java.lang.String, java.lang.Boolean, and java.lang.Object.

The == operator in Java tests for equality in simple types and object identity with Objects. In effect, the == operator compares the object reference. If the references are the same (both referring to the same object in memory) the objects are said to be identical. The == operator does not test for object equality. (As can be done in C++ by overloading the == operator. Operator overloading is not supported by Java, much to the disappointment of many C++ programmers who like to write arcane and obscure code.)

The equals() method in Java is intended to test object equality. Two objects are considered to be equal (assuming they are not identical) when they contain the same data. For example:

String a = new String( "A string" );
String b = new String( "A string" );
 
if ( a == b ) {
    // This is false
}
 
if ( a.equals( b )) {
    // This is true
}

The strings a and b are clearly equal, but they are two different objects. For the java.lang.String class, equal() will determine if the value of the Strings are the same. For java.lang.Boolean, equal() will compare the boolean values of the objects. For java.lang.Object, equal() will test for object identity.


Topic 18: Identify the earliest point in a method at which the object referred to by a local variable becomes eligible to be garbage collected, in the absence of compiler optimization.

Assuming that there is no compiler optimization, the earliest point that a local object becomes available will be when the runtime environment knows that there are no more references to the object in question. Typically, for local objects, this is when the method ends, but there are circumstances when the developer might wish to give the runtime environment a hint that the object is no longer needed. For example, given the following code:

public void method() {
    ReallyBigObject ref = new ReallyBigObject( 10000 );
 
    // do some processing
 
    // let the RTE know that ref is no longer needed
    ref = null;
 
    // do some more lengthy processing
}

The runtime environment could collect the ReallyBigObject anytime after ref is set to null. Setting the reference to null does not guarantee that the object will be garabe collected quickly, but it does help.


Topic 19: Distinguish among guaranteed behavior of the garbage collection, finalization mechanisms, and non-guaranteed behavior.

If a finalize() method exists for an object, it is guaranteed to be called once (and only once) for the object before the object is garbage collected.

It is guaranteed that only objects with no references will be garbage collected. Java uses a mark and sweep garbage collection algorithm, which traverses all the object references, marking any objects that are referred to and then garbage collecting any objects that are unmarked.

It is not guaranteed that an object will be garbage collected. When the runtime environment exits, there may be many objects that have not been collected. This is because garbage collection runs as a separate, low priority thread and there are objects the it may never collect.


Topic 20: Write nested loops to iterate blocks with specific values in loop counter variables. (Demonstrate the use of both labeled and unlabeled versions of the break and continue keywords to modify the normal loop behavior.)

	public static void loops() {
		
		outerLoop:
		for ( int i = 0; i < 4; i++ ) {
			for ( int j = 0; j < 10; j++ ) {
				if ( i == 2 ) {
					break outerLoop;
				}
				else if ( j == 4 ) {
					continue outerLoop;
				}
			}
		}
	}


Topic 21: Write nested conditional code using if or else and switch constructs. Identify the legal argument expression types for if () and switch ().

	if ( i == 2 ) {
		break outerLoop;
	}
 
	switch ( (int)event.id ) {
		case Event.ACTION_EVENT:
			// An action happened
			break;
		case Event.KEY_PRESS:
			// A key was pressed
			break;
		default:
			// Something else happened
	}

The argument to the if() must evaluate to a boolean (unlike C/C++). The argument to switch() may evaluate to any one of the following: byte, char, short, int.


Topic 22: Demonstrate the flow of control that occurs in try, catch (), and finally constructions under conditions of normal execution, caught exception and uncaught exception. Demonstrate the throws clause to a method declaration where that method contains code that might throw unhandled exceptions. Identify what exceptions may be legitimately thrown from an overriding method in a subclass, based on the declaration of the overridden superclass method.

This is:

try {
	System.out.println( "Before throwing an exception." );
	mightThrow();
	System.out.println( "After throwing an exception." );
}
catch ( IOException e ) {
	System.out.println( "The exception is thrown." );
}
finally {
	System.out.println( "Doing the finally clause." );
}

If mightThrow() does not throw an exception, the code will print out:

Before throwing an exception.
After throwing an exception.
Doing the finally clause.

If mightThrow() throws an IOException (or a subclass of IOException), the code will print out:

Before throwing an exception.
The exception is thrown.
Doing the finally clause.

If mightThrow() throws something other than IOException (or a subclass), the code will print out:

Before throwing an exception.
Doing the finally clause.
<<Uncaught exception thrown.>>

Notice that the finally clause is run even if the exception if not caught.


Topic 23: Define classes, including member variables and member methods. Declare classes using modifiers public, abstract, or final. Declare variables using the private, protected, public, static, final, native, or abstract modifiers to those members.

 

 


Topic 24: Define the accessibility of both variables and methods from other methods in the same or other classes, when the calling method is static or non-static, when the calling method is in the same class as the target, when the calling method is int he subclass of the class containing the target, when the calling method is in a class which is in the same package as the class containing the target, when no special relationship exists between the class of the caller and the class of the target, and when the target declaration is qualified by any of the provate, protected, public, static, final, or abstract.

 

 


Topic 25: Define the consitions that might prevent a thread from executing.

It hasn't been "started" with start().


Topic 26: Write a code to create a new thread. Demonstrate the conditions for a class to implement the java.lang.Runnable interface. Write code to provide the behavior of a thread. Write code to start execution of a thread.

public class MyThread implements Runnable {
    public void run() {
        while ( true ) {
            // do something
 
            try {
                wait( 5000 );
            }
            catch ( InturreptedException e ) {}
        }
    }
 
    public static void main( String[] args ) {
        MyThread m = new MyThread();
        Thread t = new Thread( m );
        t.start();
    }
}


Topic 27: Define the behavior of a thread which invokes the wait () method of an Object. Describe the interaction between the thread, the wait () method, and the object lock. Define the behavior of a thread which invokes the notify () or notifyAll () methods of an Object. Define the interaction between the thread, the notify or notifyAll methods, the object lock flag, and any thread that is cincurrently executing a wait () method on the same Object.

When wait() is called , the Thread will block for x time or until notify() is called for the Thread. notifyAll() will call notify() for each object waiting for the object lock.


Topic 28: Write a code to implement the paint () method of a java.awt.Component class. Describe the interactions between the methods repaint () and update ().

	public void paint( Graphics g ) {
		int x = 20;
		int y = 10;
		
		// draw a string
		g.drawString( "Hi there!", x, y );
		
		// draw a line to (x,y)
		g.drawLine( 0, 0, x, y );
		
		// draw a 38x18 rectangle
		int w = 38;
		int h = 18;
		g.drawRect( x, y, w, h );
	}

repaint() requests the update from the peer. The peer calls update(). update() clears the area and calls paint(). paint() does the painting.


Topic 30: Describe the appearance, at the handleEvent () and action () methods in the java.awt.Component class, of mouse clicks and <return> or <enter> keystrokes on each of these components: java.awt.TextField, java.awt.Panel, and java.awt.Canvas.

action() is called when the <Return> or <Enter> key is pressed in a java.awt.TextField.

All other events (including mouse clicks) for java.awt.TextField, java.awt.Panel, and java.awt.Canvas can only be caught in handleEvent().


Topic 31: Recall the type and significance of the return value from the handleEvent () and action () methods of the java.awt.Component class.

Both action() and handleEvent() return boolean values, to signify that they have (or have not) fully dealt with the event.


Topic 32: Construct a java.awt.TextArea or java.awt.List that prefers to display a specific number of lines. Construct a java.awt.TextArea or java.awt.TextField that prefers to display a specific number of columns. Describe the significance of a column where one of these components is using a proportional (variable) pitch font or a fixed pitch font.

List l = new List( rows );
TextField t = new TextField( cols );
TextArea a = new TextArea( rows, cols );

If the Font used for a multicolumn component (TextField or TextArea) is proportional, the component must guess at a maximum width, based on the width of the widest character in the Font (from FontMetrics). For a fixed pitch Font, all the characters are the same width and the width of the component can be calculated exactly.


Topic 33: Construct an HTML applet tag to embed and applet in a Web page. Control the width and height of the applet. Supply named parameter values to the applet. Write code in an applet that reads the value of a named parameter specified in the applet tag.

<applet code="AppletTest.class" width=200 height=200>
<param name="city" value="Atlanta">
<param name="state" value="Georgia">
</applet>
 
public class AppletTest extends Applet {
	public void init() {
		String city = this.getParameter( "city" );
		String state = this.getParameter( "state" );
	}
}


Topic 34: Demonstrate the use of the methods show (), hide (), enable (), disable (), size (), setForeground (), and setBackground () for a java.awt.Component class.

show() displays the Component, adding it to the user interface.

hide() hides the Component, removing it from the user interface.

enable() and disable() make the Component sensitive and insensitive, respectively, to user input.

setForeground() and setBackground() set the foreground and background of the Component to the passed-in colors.

Check out the java.awt.Component API docs for futher information.


Topic 35: Demonstrate the use of the methods add (Component) and add (String, Component) of the java.awt.Container class. List the displayable classes in the java.awt package that are valid arguments to these methods and those which are not valid.

add(Component) will add the specified Component to the java.awt.Container. The String from the add(String, Component) is sent to the LayoutManager for the Container. The String is passed to the LayoutManager by the addLayoutComponent() method.


Topic 36: Distinguish between AWT classes which are directly responsible for determining component layout and those which are responsible for implementing that layout.

The LayoutManager determine the layout, the Container does the layout.


Topic 37: Change the layout scheme associated with the AWT container.

Use setLayout() for the Container with the new LayoutManager.


Topic 38: Describe the effect of invoking overridden methods in base and derived classes.

Given the following class definitions:

class First {
	public String str = "first string";
	
	public String value() {
		return this.str;
	}
}
 
class Second extends First {
	public String str "second string";
	
	public String value() {
		return this.str;
	}
}

And the following code:

First first = new Second();
System.out.println( "first.str = " + first.str );
System.out.println( "first.value() = " + first.value() );

The output will be:

first.str = first string
first.value() = second string


Topic 39: Define which expressions are executed, and their resulting vlaues, in compound expressions involving the operators &, |, &&, and ||.

 

 


Topic 40: Identify the effect of assignment and modifying operations upon objects, reference variables, and primitive variables. Identify the effect that passing variables into methods and performing assignments and other modifying operations in that method has upon objects, reference variables, and primitive variables. Describe the output from a program performing these operations by studying the source.

See exercise.


Topic 41: Write code to create and throw an Exception given a specified test that returns true. Write the correct method declaration to support this behavior.

 

 


Topic 42: Describe the prototype of the default constructor. List the circumstances under which the default constructor is created and the circumstances which inhibit implicit creation of a default constructor.

 

 


Topic 43: Evaluate statements regarding thread scheduling.

 

 


Topic 44: Write code to create a new thread of execution, using both the Runnable interface and the Thread class.

 

 


Topic 45: Demonstrate the use of the synchronized keyword to require a thread of execution to obtain an object lock prior to proceeding.

 

 


Topic 46: Identify the return value of an overridden handleEvent () or action () method to control propagation of the event up the container hierarchy. Select from a list valid reasons why an event might be passed up a container hierarchy.

Both handleEvent() and action() return boolean values. This boolean indicates whether or not the event was handled in the overridden method. The return value indicates to the calling method (usually postEvent() or handleEvent() from the Container). Returning true indicates indicates that the event was completely handled and that no further action should be taken, usually by the Container (or its Container). Returning false indicates that the overridden method does not handle the event and that the parent (Container) should.


Topic 47: Select from a list given descriptions using BorderLayout, FlowLayout, and GridLayout. Select from a list strategies to achieve a dynamic resizing of a Component in the horizontal, vertical, both, or neither directions.

 

 


Topic 48: Select from a list all the operators which are legal in String expressions.

Check out the java.lang.String API info, there are too many to list here.


Topic 49: Demonstrate the use of the following String methods: lenght (), toUpperCase (), toLowerCase (), equals (), equalsIgnoreCase (), charAt (), concat (), indexOf (), lastIndexOf (), substring (), toString (), trim ().

First, check out the java.lang.String API info. It contains complete details on the above methods. Second, the only method mentioned above that is not completely obvious (to me, at least) is trim(). It simply truncates trailing whitespace in a String.

Something to remember as well is that the contents of a String cannot be changed. All operations and methods called on a String return new Strings. This is important to remember when working with Strings. If you need to modify the contents of a String, use a java.lang.StringBuffer.


Topic 50: Write code that constructs "chains" of InputStream and OutputStream objects using the subclasses of FilterInputStream and FilterOutputStream. Select from a list the valid constructor arguments for FilterInputStream and FilterOutputStream subclasses.

InputStreams and OutputStreams are typically chained together to create more complex and flexible means of input an output. To accomplish this, Input- (or Output-) Streams can be constructed from other InputStreams. For example, the following code:

DataInputStream in = new DataInputStream( 
	new BufferedInputStream( 
		new FileInputStream( filename )));

will open a file for reading, buffer the input (which makes a significant speed improvement) and allow advanced reading of the input, using DataInputStream.readLine() and DataInputStream.readFloat().

Output streams can be chained in the same way:

PrintOutputStream out = new PrintOutputStream( 
    new FileOutputStream( outFilename ));


Topic 51: Write code to read, write, and update files using FileInputStream, FileOutputStream, and RandomAccessFile objects. Describe the permanent effects on the file system of constructing and using each of these objects.

 

 


Topic 52: Write code that uses objects of the File class to navigate a file system.

The following code sample will print the directory tree starting at a given directory:

	public static void printTree( String name ) {
		File dir = new File( name );
		System.out.println( ">> " + dir );
 
		if ( dir.isDirectory()) {
			System.out.println( "Directory: " + name );
			String[] files = dir.list();
			for ( int i = 0; i < files.length; i++ ) {
				printTree( name + "/" + files[i] );
			}
		}
		else {
			System.out.println( "  File: " + name );
		}
	}

Key points of this code are: Creating a new File object with a file name, checking to see if it is a directory (with File.isDirectory()) and getting a list of the files in the directory (with File.list()).


Topic 53: Identify the sequence of Component methods involved in redrawing areas of an AWT GUI under exposure and programmed redraw conditions. Distinguish between methods invoked by the user thread and those normally invoked by AWT thread.

When the Component needs to be redrawn, the redraw() method for the Component is called. redraw() requests a redraw from its peer , and that request is eventually granted by the peer by calling update() for the Component. update() clears the Component and calls paint() on the Component. paint() draws the picture on the Graphics for the Component.

The programmer can call the redraw() method directly when the Component needs to be redrawn.


Topic 54: Write code for any overridden method that invokes the parental method, using super ().

public class SuperClass {
	public void method() {
		System.out.println( "In SuperClass method" );
	}
}
 
public class SubClass extends SuperClass {
	public void method {
		super.method();
		System.out.println( "In SubClass method" );
	}
}
	public static void main( String[] args ) {
		SubClass a = new Subclass();
		a.method();
      	System.out.println( "In main" );
	}

The call to main() above will result in the following results:

In SuperClass method
In SubClass method
In main


Topic 55: Distinguish between appropriate and inappropriate circumstances for calling parental handleEvent () and action () methods in a user-written subclass of an AWT Co[m]ponent from this list: Button, ScrollBar, List, TextField, and TextArea.

When would you want to call super.action()? If you implement a custom component that overrides action(), any component the subclasses your custom component should return the value of super.action() in the action() method if that method does not handle the event. It is good programming practice to call super.action() just to be safe.

When overriding handleEvent() to capture events that action() does not capture (see below), it is necessary to call super.handleEvent() if you override action() as well.

The action() method is called for the following objects under the following conditions:

Button

The Button was clicked.

List

An item was double-clicked.

TextField

The <Return> key was typed.

To catch any other events on the listed classes (Button, ScrollBar, List, TextField, and TextArea), the handleEvent() method must be used.


Topic 56: Identify the following methods of the Graphics class: drawString (), drawLine (), drawRect (), drawImage (), drawPolygon (), drawArc (), fillRect (), fillPolygon (), fillArc (). Write code to use these methods in paint (). Write code to obtain a suitable Graphics object from an Image. Identify appropriate use of the Image and Graphics classes.

The following code will draw some stuff:

	public void paint( Graphics g ) {
		
		// draw a string
		int x = 20;
		int y = 10;
		g.drawString( "Hi there!", x, y );
		
		// draw a line to (x,y)
		g.drawLine( 0, 0, x, y );
		
		// draw a 38x18 rectangle
		int w = 38;
		int h = 18;
		g.drawRect( x, y, w, h );
		
		// drawImage needs an ImageObserver
		g.drawImage( testImage, x, y, this );
		
		// drawPolygon needs a Polygon
		Polygon p = new Polygon( {x,40,60}, {y,20,40}, 3 );
		g.drawPolygon( p );
		
		// draw an arc from 0 to 90 degrees
		int start = 0; // degrees
		int finish = 90; // degrees
		g.drawArc( x, y, w, h, start, finish );
		
		// fill in a rectangle
		g.fillRect( x, y, w, h );
		
		// fill in a polygon
		g.fillPolygon( p );
		
		// fill in an arc
		g.fillArc( x, y, w, h, start, finish );
	}

To get the Graphics from an Image use:

Graphics g = someImage.getGraphics();

draw() could be used to draw the graphics into someImage. someImage could then be drawn into another Graphics with drawImage().

[ top of page ]