You are on page 1of 267

Java Workshop

• By Boris Chan
• 2002 July
Workshop Arrangement

Web Page Design Basic 2 hours Day 1


Flash 4 hours Day 1
Into to Java 2 hours Day 2
Basic Java Programming 4 hours Day 2
Java Applet 6 hours Day 3
Web & Java 6 hours Day 4
Into. To Multimedia 2 hours Day 5
Multimedia & Java 4 hours Day 5
Objectives of Java Section
• Understand Basic of
• Java Programming
• Object-Oriented Approach
• Able to
• Use JDK & API Documents
• Java Application & Applet
• Know how to
• Deploy Java Application & Applet
Topics of Java Section
• Introduction to Java
• Programming Basic
• Java Development Kit (JDK)
• Integrated Development Environment (IDE)
• Programming Exercise
• Java Application
• Java Applet
• Package: java.io, java.lang, java.util
Intro. To Java
• The Green Project In 1991 By James Gosling
• Named “Oak” (Tree)
• Rename to “Java” (Coffee)

Father of Java: James Gosling


The Green Project Stopped
• Market of Intelligent Consumer Electronics
Devices

• E.g. Video on Demand


• In 1991, Market needs lag behind Technologies
• Sun Microsystems lost a Major Contract
Internet Takes Off
• 1993, NCSA Mosaic released
• Easy-to-use Interface
• Graphical Interface enhance
Documents Sharing

• 1995, Netscape licensed Java Technology

• Microsoft Internet Explorer


Why Java in Internet ?
• Dynamic Delivery of Contents
• Security
• Cross-Platform
• Interactive on the Web
• Object-Oriented Programming Language
• Java Foundation Class (JFC)
• Large Development Community
• Technical Supports from various sources
Java Terminology
• Java Development Kits (JDK) Versions
• JDK [1.0] , [1.0.2] ;
• JDK [1.1.0] , [1.1.1] , [1.1.2] … [1.1.8] ;
• JDK [1.2.1]

• Java Editions
• Java 2 Platform, Enterprise Edition (J2EE)
• Java 2 Platform, Standard Edition (J2SE)
• Java 2 Platform, Micro Edition (J2ME)
Java Terminology
• Java Runtime Environments (JRE)
• Virtual Machine (VM)
• Java Package & Library (e.g. Lib, JAR, ZIP)
• Application Program Interface (API)
• Java Card & Smart Card
• Multi-thread (ready for parallel computing)
• Bytecode & semi-compilation
Java 2 Architecture
Servers
Servers&&Enterprise
Enterprise
Computers
Computers
Desktop
Desktop&&Personal
Optional Personal
Computers
Computers
Packages
Optional High-end
High-endConsumer
Consumer
Packages Devices
Devices Low-end
Low-endConsumer
Consumer
Devices
Devices

J2ME
J2EE
J2SE Personal Profile
Smart
SmartCard
Card
Foundation Profile MIDP
Java Card
CDC CLDC APIs

Hotspot VM
Java Virtual
CVM Machine
KVM CardVM
Host Operating System
Computing Platform Mapping
Java Technology
• A Programming Language
• Object-Oriented
• Improved from C++
• Semi-compilation (Bytecode)
• Virtual Machine (Multiple Platforms)
• Development Environment
• SDK provided by Sun Microsystems
• Development Tools (Sun forte, MS J++)
• Java Foundation Classes
Java Technology
• Deployment Environment
• Browser (or Applet Viewer) for Java Applet
• JRE for Java Application
• Documentation
• Javadoc included in JDK for Document Gener
ation
• Documents for Java Classes & API provided b
y Sun Microsystems
Sun’s Definition
• Java is a
“simple, object-oriented, distributed, interpreted,
robust, secure, architecture-neutral, portable,
high-performance, multi-threaded, & dynamic”
language.
Java is Simple
• Improved from C++
• Java has NO
• Header file (for definition)
• Pre-processor coding (#ifdef… #endif)
• Pointer
• Semantic problem => Syntactic error
• Compiler checks that Object needs initiation
• Exception Handler is mandatory for
Some Objects
Java is Object-Oriented
• Java programming is Class-based
• Class is generalization of objects
• Class has attributes (variables)
& methods (functions)
• Class can inherit properties to other classes

// webClock has properties of Applet


class webClock extends Applet ...
{...
}//class webClock
Java is Distributed

Source Computer
Java Applet
Java Program Compilation (Byte-codes)

Internet

Verification Client
Sand-box
Java
Execution Restricted
Byte-codes
Java is Interpreted & Portable
• Install JVM before running Java program
• All major Operating System (OS) have JVM
• Semi-compiled Bytecode can be ported to
multiple platforms => money saving
Java is Robust
• Java program can access memory
in a restricted way
• Java supports comprehensive
exceptions handling
• Java can hardly causes a computer to crash !
Java is Secure
• Java has NO pointer
• Java is statically typed
• Data structure must be defined before use
• Data Type mis-match / error detected by
java compiler (javac)
• Minimize run-time checking & error during
interpretation
• Automatic Garbage Collection
• Bytecode is verified before execution
Java is Architecture Neutral
• Java is the same on every computer
• Integer is 32-bits
• Character is 2-byte Unicode
• Java targets on virtual CPU
meanwhile JVM is Machine specific
Java is High Performance
• In “Vanilla” JVM interpreter Mode, Java program
runs about 20 times slower than C program
But is acceptable for many applications

• JIT (Just In Time) Compilers in SDK 1.2


• “Hotspot” Optimization in SDK 1.3
Java is Multi-threaded
• A Java program can have more than one thread
of execution
• e.g. taking input from user while having an active
clock at the background
• Provides easy-to-use features for multi-thread
programming
• Java threads are usually mapped onto OS
threads => advantages for multi-processor
machines
Other Advantages

• Garbage Collector
• built-in program in Java to scan memory and
automatically frees any memory chunk that is no longer
in use
• => easier memory management for Java programmers

• Java is small
• Java is designed to run on small computers, including
many controllers in electronic appliances
• Java can run with about 4M RAM
Other Advantages

• Java Native Includes (JNI)


• Java Program can interface with
software libraries in other language
implementation (e.g. C/C++)
Other Advantages

• Garbage Collector
• built-in program in Java to scan memory and
automatically frees any memory chunk that is no longer
in use
• => easier memory management for Java programmers

• Sand-Box Approach
• Applet cannot read/write files on client machine
• Applet cannot make network connection
• Applet cannot use/share any library in other languages
• Applet cannot invoke/run local application
• Applet can be authenticated by Digital Cert.
Java Application & Applet
• In terms of execution path,
Java program can be
• Applet: a small program running on browser
• Application: running with independent process
Java-enabled Browser
• Major browsers has embedded JVM including :
• Netscape 4.x or later
• Microsoft IE 5.x or later
• JVM also available for IE on Windows XP
Java Running Anywhere
• Java Applets & Applications
• JavaOS
• Netware, OS/2, Macintosh
• JavaStation, Java Chip
• Java Card, Java Ring
• Java Phone
Java Everywhere
---- Section Break ----

Basic Java Programming

• Command-line based JDK


free download from Sun Microsystems
• http://java.sun.com/
• We use JDK 1.3
• Quick Revision:
• JDK 1.0, 1.0.2
• JDK 1.1.0, 1.1.1, 1.1.2 … 1.1.8
• JDK 1.3.1
• Java 2 SDK 1.2.2
• Java 2 SDK 1.3.0, 1.3.1
• Java 2 SDK 1.4
JDK includes
• Java compiler (javac)
• Run-time Interpreter (java)
• Applet Viewer
• Debugger
• Diassembler
• Header file Generator (javah)
• Document Generator (javadoc)
• API Implementation & Documentation
• Sample Programs
Java Compiler
• Javac compiles source code into Bytecode
e.g. javac webClock.java => webClock.class
• Javac generates ONE class file
• Syntax: javac ClassName.java
• E.g.
C:\myJavaSrc> javac Bmi.java
C:\myJavaSrc> dir Bmi.*
2002/07/21 07:22p <DIR> .
2002/07/21 07:22p <DIR> ..
2002/07/21 07:26p 828 Bmi.java.bak
2002/07/21 07:26p 799 Bmi.java
2002/07/21 07:57p 736 Bmi.class
Run-time Interpretor
• Acts as command-line tool for running non-graph
ical Java programs
• Syntax: java ClassName
• E.g.
C:\myJavaSrc> java Bmi
BMI Conclusion
========== =======================
18.4/less Underweight
18.5-24.9 Normal
25.0-29.9 Overweight
30.0-34.9 Obesity(High)
35.0-39.9 Obesity(Very High)
40.0/above Obesity(Extremely High)
Applet Viewer
• Minimal test bed for Java Applets
alternative to Browser
• Syntax: appletviewer URL
• E.g.
C:\myJavaSrc> appletviewer Bmi.html

• Note: The Bmi.html must contains:


<applet
code="Bmi.class" width="300" height="300">
</applet>
Java Debugger
• Command-line utility to debug Java Application
• Syntax: jdb ClassName
• E.g.
C:\myJavaSrc> jdb Bmi
Disassember
• Disassember generate all public data & method
of a class
• Syntax: javap ClassName
• E.g.
C:\myJavaSrc> javap Bmi
Compiled from Bmi.java
public class Bmi {
public static void main(java.lang.String[]);
}
Header File Generator
• Generates Header File of C language
• Usually used for Java Native Include (JNI)
• Syntax: javah ClassName
• E.g.
C:\myJavaSrc> javah Bmi
C:\myJavaSrc> dir Bmi.h
2002/07/21 09:05p 2,006 Bmi.h
Document Generator
• Generates API Document directly from
Java Source Code
• Syntax: javadoc ClassName.java
• E.g.
C:\myJavaSrc> javdoc Bmi
Loading source file bmi.java...
Constructing Javadoc information...
Building tree for all the packages and classes...
Building index for all the packages and classes...
Generating overview-tree.html...
...
Java API Document
• At URL : http://java.sun.com
• Download for local installation
• Refer online
Java API Document online
Sample Programs
• Animator • ImageTest
• ArcTest • JumpingBox
• BarChart • MoleculeViewer
• Blink • NervousText
• BouncingHeads • ScrollingImages
• CardTest • SimpleGraph
• DitherTest • SpreadSheet
• DrawTest • TicTacToe
• Factal • TumblingDuke
• GraphicsTest • UnderConstruction
• GraphLayout • WireFrame
• ImageMap
Three Development Platforms
• Enterprise Edition (J2EE)
• Develop Web Server Side Application
• Standard Edition (J2SE)
• Develop Java Applications & Applets
• Micro Edition (J2ME)
• Develop device specific Applications
• E.g. Mobile Phone
IDE for Java
• Integrated Development Environment (IDE)
• Visual Editor
• Compiler & Builder
• Debugger
• Class Libraries
• Context Specific Help
Well-Known IDE
• FORTE by Sun
• VisualAge by IBM
• WebSphere’s Studio by IBM
• JBuilder by Borland
• JDeveloper by Oracle
• Visual J++ by Microsoft
• PowerJ by Sybase
• CodeWarrior by MetroWerk
• Visual Café by WebGain
---- Section Break ----

Developing Java Application
• Body Mass Index : Bmi.java
1. Display info. only
2. Accept input via arguments
3. Accept input via command-line
4. Record user info. & BMI in text file
5. Retrieve user info. from text file
Development Basic
• How to compose source code
• How to compile
• How to run
• How to debug

• Environments Setting
• Path
• Classpath
Java Language
• Programming Structure
• Comments
• Package Commonly Used
• Data Structure
• Logic & Flow Control Operators

• Advanced Data Structure


• Method Overloading
Programming Structure
public class Bmi
{
/**
* display BMI Lookup Table on standard output
*/
public static void main( String argv[] ) //single line comments...
{
System.out.println("BMI Conclusion");
System.out.println("========== =======================");
System.out.println("18.4/less Underweight");
...

• Note :
• public static void main( String argv[ ] )
• Comments are enclosed by /* */
• Single line Comments started by //
Package Commonly Used
• java.io.*
• System.out.print( … )
• System.out.println( … )
• BufferedReader
• java.lang.*
• String
• java.util.*
• StringTokenizer
Data Structure : Primitive

Primitive Type Storage Size Value Range


byte 8-bit -128 to 127
short 16-bit -32,768 to 32767
int 32-bit 10-32 to 1032 –1
long 64-bit 10-64 to 1063 –1
float 32-bit 6 significant digits (10-46 to 1038 )
double 64-bit 15 significant digits (10-324 to 10308 )
char Unicode char
boolean Boolean true & false
Data Structure : String
• java.lang.String
• String is Java object instance

• case one : String s1 = new String(“Hello


World”);
• case two : String s2 = “Hello World”;

• Both case one & two are the same


• case two is more simple, more preferable
1 Dimensional Array

public void anyMethod() Stack memory Heap memory

{ 0
iArray
int iArray[]; 1
2
iArray = new int[10];
:
... :
iArray[9] = 100;
...

9
2 Dimensional Array
public void anyMethod()
{
int i2DArray[];
i2DArray = new int[5][10];
i2DArray[2][3] = 2300;
...
Stack memory Heap memory

i2DArray
Initializing Array
// a single-dimensional array of ints
int [] iArray;
iArray = new int[10];
for (int i=0; i<10; i++)
iArray[i] = 0;

// a two-dimensional array of ints


int [][] i2DArray;
i2DArray = new int[5][10];
for (int i=0; i<5; i++)
for (int j=0; j<10; j++)
i2DArray[i][j] = 0;
Alternative of Initializing Array
// a single-dimensional array of ints
int [ ] iArray = {0,0,0,0,0,0,0,0,0,0};

// a two-dimensional array of ints


int [ ][ ] i2DArray = {{0,0},{0,0,0}};
Binary Operations
• Assignment
• int iNumber1 = 1;

• Comparison (see also Logic Expression)


• int iNumber2 = iNumber1>1 ? iNumber1 : 0;
• if ( iNumber1 == iNumber2 ) {

} else {

}
Logic Expression

X Y X && Y X || Y !X
false false false false true
false true false true true
true false false true false
true true true true false
If-Else Flow Control
• Conditional Branch
• if – else
• if – else if – else
Switch-Case Flow Control
• switch ( someChar )
{
case ‘a’ : …; …; break;
case ‘b’ :
if (…); …;
break;
case ‘c’ :
case ‘d’ :
case ‘e’ : …; …; break;
default:
break;
}
For-Loop Flow Control
• For-Loop
• for ( int i=1; i<10; i++ ) {

}
For-Loop & Continue
• Where to use?
• in a loop
• Purpose:
• To skip the remaining statements and continue for
the next iteration
• E.g.

for (int j=1; j<6; i++) {


if (certain_condition_happen)
continue;


}
Continue & Label
• Where to use?
• Label can be used only at the start of a loop
• Usually used to label the outer loop in a nested loop
construct
• Because Java does not allow label to be arbitrarily
used anywhere, the use of label should not be viewed
as a poor programming practice
Continue & Label (E.g.)
// with continue & label

public class Continue3 {


public static void main(String [] args) {
int r = 0;
outer: for (int i=1; i<3; i++)
for (int j=1; j<6; j++) {
if (j == 2) continue outer;
r = i*j;
System.out.println(i + " * " + j + " = " + r);
}
}
}
While-Loop Flow Control
• While-Loop
• while ( logical expression ) {

if ( conditions )
break;


}
Try-Catch(Exception) Block
• Try-Catch( Exception ) Block
• try {
// normal code …



} catch ( Exception e ) {
// reporting code

}
• Will mention more…
Object Reference
• Reference “points” to an object
• Memory address of the object
• Reference likes other data type
• String, Array, etc.
• E.g.
• Button b = new Button();

b
0f1c
Button object
Object Reference (E.g.)
For primitive types :

int i = 3; // i contains the value 3


int j = i; // j contains a copy of the value in i
i = 2; // Changing i doesn't change j
// now, i == 2 and j == 3.

For referenced type :

Button p, q;
p = new Button(); // p refers to a Button object
q = p; // q refers to the same Button
p.setLabel("OK"); // A change to the object through p...
String s = q.getLabel(); // .. is also visible through q
// s now contains "OK"
---- Section Break ----

Developing Java Applet
• Body Mass Index : Bmi.java
1. Display info. only
2. Accept input via arguments
3. Accept input via GUI
Java Applet sample codes
• Display BMI Lookup Table by Applet
public void paint( Graphics g )
{
String ltable = getLookupTable();
StringTokenizer t = new StringTokenizer( ltable, "\n" );
int n = t.countTokens();
for( int i=0; i<n; i++ )
{
String s = t.nextToken();
g.drawString(s, 50, (50+(i*20)));
}//for(i)
}
Execution of Java Applet

applet is loaded
start paint

Restoring a Minimizing a
init page
page
destroy

stop
discarding a page
Applet Methods

1. void init() Called once after an applet has been loaded. A


place to do initialization.

2. void start() Called to inform the applet to take any action


e.g. starting threads. It is called after init() and
whenever the window is restored

3. void stop() Called to inform the applet to stop its execution.


e.g. stopping threads. It is called whenever the
window is minimized.
Applet Methods

4. void paint() Called to paint on the applet. It is called whenever the


applet is exposed as a result of de-iconification,
covering windows being removed, or self-window
being resized.

5. void destroy() Called to tell the applet that it's being reclaimed
from the system and that it should destroy any
resources it has allocated. An applet that uses
threads would destroy them in this method.
However, stop() will always be called before
destroy(). It is called whenever the window is closed.
Control Display Window
1. control the width & height by <Applet> tag
• <Applet
code=Bmi.class width=150 height=150>
</Applet>

2. use resize() in init()


• public void init( ) {
resize( 150, 150 );

}
Applet gets input from User
import java.awt.*;
import java.applet.*;

public class GetInput1 extends Applet {


TextField textField;

public void init() {


textField = new TextField(20);
add(textField);
}
public void paint(Graphics g) {
String s = textField.getText();
g.drawString(s, 40, 50);
}
public boolean action(Event event, Object arg) {
repaint();
return true;
}
}
Explanation

1. TextField is a class defined in Java's standard API, representing a text


field for input
2. For any textfield, it can invoke the method getText() to get the input t
ext from keyboard buffer
3. The action() method is one of the ways in Java to handle events. Itwil
l attend to any events caused by pressing the ENTER key, or any Butt
ons defined. The arguments Event and Object are not used in this sa
mple.
4. repaint() is to update the display and call the paint() method again
5. return true; is an indication to the Java runtime that the event is hand
led and need no further handling
Invoke Applet by JavaScript
• Applet can be invoked in 2 ways
• Implicitly loading by browser
• Explicitly loading by JavaScript in HTML
Invoke Applet by JavaScript (E.g)
<html>
<head><title>Body Mass Index</title>
<script language="JavaScript">
function callApplet() {
val1 = parseInt(document.forms[0].weight.value);
val2 = parseInt(document.forms[0].height.value);
document.Bmi.getMeasure(val1, val2);
}
</script>
</head>

<center>
<body>
<h1>Body Mass Index</h1>
<font size=5>
Number:
</font>
Invoke Applet by JavaScript (E.g)
<form>
<input type=text name=height value="0" size=12>
<input type=text name=weight value="0" size=12>
<input type=button name=compute value="Compute"
onclick="callApplet()“ >
</form>
<hr>
<applet
code=Bmi.class name=Bmi width=150 height=150>
</applet>
</center>
<hr>
<a href=“Bmi.java">The Source</a>
</body>
</html>
---- Section Break ----

Packaging
• To facilitate the organization of classes, similar
classes are grouped together as a package

• To use a package, use the keyword import


– E.g. import java.awt.*;

• To define the class under a package, use the ke


yword package
– E.g. package myPack.test;
Packaging Example
• “Class” based
package myPack.test;
import java.io.*;

public class Bmi


{
/**
* display BMI Lookup Table on standard output
*/
public static void main( String argv[] )
{
System.out.println("BMI Conclusion");
System.out.println("========== =======================");
System.out.println("18.4/less Underweight");
...
Packaging Highlights
• The keyword package must precede the import k
eyword
• To compile a java source under package
– javac –d . Bmi.java
• A subdirectory myPack/test is created under the
current directory and the Bmi.class resides in it.
• To run a class under package
– java myPack.test.Bmi
Default Package
• Even if we don’t give an explicit package name
to a class, it is still under the default package
• All classes without a package name, and put
under the same directory, are belonging to the
same default package
---- Section Break ----

Other Common Operators
Precedence Operator Operand Type(s) Operation Performed
1 ++ arithmetic pre-or-post increment (unary)
-- arithmetic pre-or-post decrement (unary)
+, - arithmetic unary plus, unary minus
! boolean logical complement (unary)
(type) any cast
2 *, /, % arithmetic multiplication, division, remainder
3 +, - arithmetic addition, subtraction
+ String string concatenation
4 <, <= arithmetic less than, less than or equal
>, >= arithmetic greater than, greater than or equal
instanceof object, type type comparison
5 == primitive equal (identical values)
!= primitive not equal (different values)
== object equal (refer to same object)
!= object not equal (refer to different objects)
6 && boolean conditional AND
7 || boolean conditional OR
8 ?: boolean,any,any conditional (ternary) operator
9 = variable,any assignment
*=, /=, %=, +=, - variable,any assignment with operation
=
Operators Highlights
• Auto-increment
int i = 0;
i++;
i becomes 1.
• Type casting
int i = (int) 10.00;
– To change the data type before assignment
• Type checking at runtime
Button b = new Button();
:
:
if (b instanceof Button) { // true
…}
Operator Highlights
• Conditional Operator ?:
int i=1, j=2;
int max = (i>j) ? i : j;
– max contains 2, why?
– First operand (i>j) is the condition. If it is true, returns the
second operand (i), else returns the third operand (j)
• Assignment operator +=
int j = 10;
j += 5; // equivalent to j = j + 5
Operator Precedence

• Smaller number means higher precedence


• Operator with higher precedence will be executed
first Operator Precedence
• e.g. + 3
– boolean b = 3 + 4 > 5; > 4
– Is b true or false? = 9
– Based on the operator precedence,
it should work out as
• boolean b = (3 + 4) > 5;
– Ans: b = true
---- Section Break ----

Why OO Programming
There are so many things in our chaotic world.

Application development is to solve real-life problem by


modeling these things and the system they belong to in
terms of attributes and behaviors.

Thus, every system involves definitions of data items and


processing routines.

We would like to ask : Is there a good way to model the


system to reflect the reality as close as possible and
improve the productivity of application development
in such endeavor ?
OO Prinicples
1. Define classes
• Java allows programmer to define classes
2. Data encapsulation
• Data and methods inside a class can be shielded from
direct access by other classes
3. Inheritance
• The data and methods of a parent class can be
descended to its child class
4. Polymorphism
• The same method call can invoke different logic
Define Java Class
• A class is a collection of data and methods that operat
e on that data, together they define the contents and c
apabilities of some kind of object
• e.g. Circle
• data : (x, y) of centre and radius
• methods : compute the circumference, area; check if some
points are inside the circle; resizing ...
• every circle is unique, but all of them have intrinsic general
properties => Class definition
• Class of circles serves as an abstract model for the co
ncept of a circle
• Classes are software blueprints for objects
Defining Circle Class
// Circle.java
public class Circle {
public double x, y, r;

public double circumference() {


return 2 * 3.14159265 * r;
}

public double area() {


return 3.14159265 * r * r;
}
}
Objects
• Objects are instances of a class
• The term object and instance are used
interchangeably
• e.g. Circle
• We define the Circle class, but we need a particular circle
to work with - a single circle object
• Define a reference variable c of Circle type
• Circle c;
• C is NOT an object itself
• We need one more statement to create the object
new Circle();
• Putting together
• Circle C = new Circle();
Data Encapsulation
• Process of packaging an object's data together
with its methods
• Benefits :
• Hiding of implementation details from other
objects
• The data in the object will not be corrupted so
easily
• External portion of an object is referred as the
object's interface
---- Section Break ----

Exception Handling

Exception - a signal that indicates that some sort
of exceptional condition (e.g. error) has occurred

Throw an exception - to signal an exceptional
condition

Catch an exception - to handle an exception

Exceptions make error handling more regular
and logical by appropriate grouping of handling
code into one place
Propagation of Exception
• Exceptions propagate through the lexical block
structure of a Java method, then up the method
call stack
• If not caught by block of code that throws it, the
exception will propagate to the next higher
enclosing block of code, ... and so on
• If it is never caught, it will eventually propagate
to the main() method and causes the Java
interpreter to print an error message, a stack
trace and exit
Propagation of Exception (E.g.)

A-Call-B

exception
B-Call-C

exception handler
C
call stack
Exception Object
• java.lang.Throwable class has two child classes
– java.lang.Error

problems related to dynamic loading, virtual
machine

Unrecoverable and should not be caught
– java.lang.Exception

Minor errors, e.g.

EOFException

ArrayIndexOutOfBoundsException

may be caught and recovered
Programming of
Exception Handling
• Two approaches

Catch the exception object

Propagates the exception object to the caller
method
Catch Exception
• try/catch/finally "triplets“
• try
• establishes a block of code to have its exceptions
and normal exits handled
• catch
• catch and handle specified types of exceptions
• finally
• specifies "clean-up" code; guaranteed to be
executed regardless of how the code in the try
block exits
Try-Catch-Finally Statement
try {
// Normally this code runs from the top of the block to the bottom without problems.
// But it sometimes may raise exceptions or exit the block via a break, continue,
// or return statement.
}
catch(SomeException e1) {
// Handle an exception object e1 of type SomeException or of a subclass of that type.
}
catch(AnotherException e2) {
// Handle an exception object e2 of type AnotherException or of a subclass of that type.
}
finally {
// Always execute this code, after we leave the try clause, regardless of whether we leave it:
// 1) Normally, after reaching the bottom of the block.
// 2) With an exception that is handled by a catch.
// 3) With an exception that is not handled.
// 4) Because of a break, continue, or return statement.
}
Propagation of Exception Object

Any method that may generate exceptions must
either
– catch the exception, or
– propagates the exception by specifying the type of
exception with a throws clause in the method
declaration

public void open_file() throws IOException {


// Statements here that might generate an uncaught java.io.IOException
}

public void myfunc(int arg) throws MyException1, MyException2 {


// something here
}
Create Exception Object

E x c e p t io n System-defined

M y E x c e p tio n M y O th e r E x c e p tio n User-defined

M y S u b E x c e p tio n
Three Exception Classes

class MyException extends Exception {


public MyException() { super(); }
public MyException(String s) { super(s); }
}

class MyOtherException extends Exception {


public MyOtherException() { super(); }
public MyOtherException(String s) { super(s); }
}

class MySubException extends MyException {


public MySubException() { super(); }
public MySubException(String s) { super(s); }
}
Exception Handling (E.g.)
Structure of this experiment :

main() - handle System exceptions


|
a() - handle MyException and MySubException
|
b() - handle MyOtherException
|
c() - generate the three user-defined exceptions
ThrowTest.java (1/5)
// This class demonstrates defining, throwing and handling exceptions
//
// Try invoking it in the following ways and try to understand the
// output:
//
// java throwtest - catches System exception
// java throwtest one - catches System exception
//
// java throwtest 0 - catches user-defined exception
// java throwtest 1 - catches user-defined exception
// java throwtest 99 - catches user-defined exception
//
// java throwtest 2 - produces 4
// java throwtest 3 - produces 9
ThrowTest.java (2/5)
public class ThrowTest {
public static void main(String [] args) {
int i=0;
try {
i = Integer.parseInt(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Must specify an argument");
System.exit(1);
} catch (NumberFormatException e) {
System.out.println("Must specify an integer argument.");
System.exit(1);
}
a(i);
}
ThrowTest.java (3/5)
public static void a(int i) {
try {
b(i);
} catch (MyException e) {
if (e instanceof MySubException)
System.out.print("MySubException: ");
else
System.out.print("MyException: ");

System.out.println(e.getMessage());
System.out.println("Handled at a() method");
System.exit(1);
}
}
ThrowTest.java (4/5)

public static void b(int i) throws MyException {


int result;

try {
System.out.print("i = " + i);
result = c(i);
System.out.print(“\nc(i) = " + result);
} catch (MyOtherException e) {
System.out.println(“\nMyOtherException: " + e.getMessage());
System.out.println("Handled at b() method");
System.exit(1);
} finally {
System.out.print("\n");
}
}
ThrowTest.java (5/5)

public static int c(int i) throws MyException, MyOtherException {


switch (i) {
case 0: throw new MyException("input too low");
case 1: throw new MySubException("input still too low");
case 99: throw new MyOtherException("input too high");
default: return i*i;
}
}
}
---- Section Break ----

GUI – AWT Package
• AWT - a general-purpose, multiplatform windowi
ng library
• Provides classes to
– encapsulate many useful GUI components
– manage component layout
– handle fonts, colors and other GUI-related items
• Categories
– Control classes
– FlowLayout
– Component classes
– Button
AWT Package
Container Class
Container The parent class of all components and one that
can contain other classes. Has a useful helper
object called LayoutManager

Window A top-level window that has no border

Frame A top-level window that has a border. Can have


an MenuBar object

Dialog A top-level window used to create dialogs

Panel A subclass of Container that can be used inside


other containers, allowing to make more intricate
layouts by combining them with subpanels
Container Class Hierarchy

Object

C om ponent

C o n ta in e r

W in d o w P anel

D ia lo g F ra m e
Component Classes
Component The parent class of many of the AWT classes
Basic purposes : represent something that has
a position and a size and can be painted on the
screen; receive input events

Button A GUI button for action


Canvas A general-purpose component for painting or
trapping input events

Checkbox On/Off component


Label Displays a string at a certain location
List A scrolling list of strings

Scrollbar Can be used to build scrollable canvas


TextArea A simple text-editing component
TextField A single-line text component for building forms
Frame
• The window frame for graphical applications
• Has minimize, restore, and close button on the t
op right corner
• Dialog class has only the close button
• Important methods
– setSize(250, 250) to set the frame size
– setVisible(true) to make the frame visible
Frame1.java
// Frame1.java
import java.awt.*;

public class Frame1 {

public static void main(String args[]) {


Frame f = new Frame ("Hello");
f.setSize(250, 250);
f.setBackground(Color.red);
f.setVisible(true);
}
}
Frame1.java
• Close button doesn’t work!
• Need to use event listener to perform the
close function (to be discussed later)
Panel
• A container for components
• Unlike Frame, it cannot run standalone
• Panel has to be added to a Frame
Panel1.java
import java.awt.*;

public class Panel1 {

public static void main(String args[]) {


Frame f = new Frame ("Panel1");
f.setSize(250, 250);
f.setBackground(Color.red);
f.setLayout(null);

Panel p = new Panel();


p.setSize(150, 150);
p.setBackground(Color.yellow);

f.add(p);
f.setVisible(true);
}
}
Panel1.java
Layout Manager
• To handle placement of controls in Container obje
cts
• 5 Layouts
• FlowLayout - Default layout for Panel and Applet
• BorderLayout - Default layout for Frame
• GridLayout
• CardLayout
• GridBagLayout
• Turn off the layout
• f.setLayout(null);
• Change to other layout
• f.setLayout (new FlowLayout());
FlowLayout Manager
• Components added from left to right, from top to
bottom, just like flowing water
• Default alignment is centered
• Respect components’ preferred sizes
• The default layout for Panel and Applet
Flow1.java Application
import java.awt.*;

public class Flow1 {


public static void main(String args[]){
Frame f;

button b1 = new Button("Press Me");


button b2 = new Button("Don't press Me");

f = new Frame("FlowLayout Example");


f.setLayout(new FlowLayout());
f.add(b1);
f.add(b2);
f.pack();
f.setVisible(true);
}
}
Flow Applet
import java.applet.*;
import java.awt.*;

public class Flow extends Applet {


public void init() {

add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
}
}
Border Layout Manager
• Place components according to geographic position
(N, S, E, W) and the (C)enter
• Component fills up the region
• Component’s preferred size is NOT respected
• Default layout for Frame
Border Applet
import java.applet.*;
import java.awt.*;

public class Border extends Applet {


public void init() {
setLayout(new BorderLayout());

add(new Button("NORTH"), BorderLayout.NORTH);


add(new Button("SOUTH"), BorderLayout.SOUTH);
add(new Button("EAST"), BorderLayout.EAST);
add(new Button("WEST"), BorderLayout.WEST);
add(new Button("CENTER"), BorderLayout.CENTER);
}
}
CardLayout (1/3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Card extends Applet implements Mou


seListener {
CardLayout layout;
Button b1, b2, b3, b4, b5;

public void init() {


layout = new CardLayout();
setLayout(layout);

b1 = new Button("First");
b2 = new Button("Second");
b3 = new Button("Third");
b4 = new Button("Fourth");
b5 = new Button("Fifth");
CardLayout (2/3)
b1.addMouseListener(this);
b2.addMouseListener(this);
b3.addMouseListener(this);
b4.addMouseListener(this);
b5.addMouseListener(this);

add(b1,"1");
add(b2,"2");
add(b3,"3");
add(b4,"4");
add(b5,"5");

layout.show(this, "3");
}
CardLayout (3/3)
public void mousePressed(MouseEvent e) {
layout.next(this);
}

public void mouseReleased(MouseEvent e) {}


public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
GridLayout
• Display components in the Container in a
regular-sized grid
• Component’s preferred size is NOT respected
GridLayout Applet
import java.applet.*;
import java.awt.*;

public class Grid extends Applet {

public void init() {

// grid with 2 rows and 3 columns


setLayout(new GridLayout(2,3));

add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
Add(new Button(“Six”));
}
}
GridLayout for Calculator
• Create the following Calculator applet
• Answer in ans\Calc.java
---- Section Break ----

Event Handling
• Event source
– The generator of an event, usually an GUI component
– E.g. Pressing the mouse button over an applet
• Event object
– Object that describes what happened
– Automatically generated
– E.g. a MouseEvent object is generated when a mouse
button is clicked
• Event handler
– A method that receives the event object and processes t
he user interaction
– E,g, the mousePressed() method to process the Mouse
Event object
3 Paths in Event Handling

MouseEvent
Object Event object
trapped by the event
Generates handler method
the event object

Applet mousePressed()
Event handler

Mouse click
JDK1.1 Event Model
• Even we are using Java 2 SDK 1.4, The event model
is still called JDK1.1 Event Model
• Also known as the Delegation Event Model
• Event source
• GUI components generate events. It's up to each
component to register an event handler (listener) method to
receive the event
• Event objects
• objects that are sent to registered listeners
• Event Listeners
• Methods to be defined within a class implementing the
corresponding Listener interface
Event Handling : Steps 1 & 2
1. import java.awt.event.*;

2. Define the handler class that would implements meth


ods to handle events, add implements XXXlistener i
n class definitions :

public class MouseHandler implements MouseMotionListen


er {
public void MouseDragged { …}
public void MouseMoved { …}
}
Event Handling : Step 3
3. In the class where some components would like to us
e the handler, register the components to the handler
using the appropriate addXXXListener() method,
 pubic class EventSource extends Applet {
 public void init() {
 this.addMouseMotionListener (new MouseHandler());

 }
 …
 }
Handler.java (1/2)
import java.awt.*;
import java.awt.event.*;
public class MouseHandler
implements MouseListener, MouseMotionListener {
private int last_x, last_y;
Graphics g;
public MouseHandler (Graphics g) {
this.g = g;
}
public void mousePressed(MouseEvent e) {
last_x = e.getX();
last_y = e.getY();
}
public void mouseDragged(MouseEvent e) {
int x = e.getX(), y = e.getY();
g.drawLine(last_x, last_y, x, y);
last_x = x;
last_y = y;
}
Handler.java (2/2)
// The other, unused methods of the MouseListener interface.
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// The other method of the MouseMotionListener interface.


public void mouseMoved(MouseEvent e) {}
}
Event Handler Applet
import java.applet.*;
import java.awt.*;
public class Scribble extends Applet {
public void init() {
Graphics g = this.getGraphics();
MouseHandler mh = new MouseHandler(g);
this.addMouseListener (mh);
this.addMouseMotionListener (mh);
}
}
Handler 2 in 1 (1/3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Scribble1 extends Applet


implements MouseListener, MouseMotionListener {

private int last_x, last_y;


Graphics g;

public void init() {


g = this.getGraphics();
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
Handler 2 in 1 (2/3)
public void mousePressed(MouseEvent e) {
last_x = e.getX();
last_y = e.getY();
}

public void mouseDragged(MouseEvent e) {


int x = e.getX(), y = e.getY();
g.drawLine(last_x, last_y, x, y);
last_x = x;
last_y = y;
}
Handler 2 in 1 (3/3)
// The other, unused methods of the MouseListener interface.
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// The other method of the MouseMotionListener interface.


public void mouseMoved(MouseEvent e) {}
}
Event Categories
• Events are categorized by their source, e.g
– Action (button)
– Key
– Mouse button
– Mouse motion
– Text
– Window…
• Different category of events are handled by
different Listener Interfaces
Event Categories & API (1/2)
Category of Interface Name Functions
Event
Action ActionListener actionPerformed (ActionEvent)
Item ItemListener itemStateChanged (ItemEvent)
Mouse Motion MouseMotionListener mouseDragged (MouseEvent)
mouseMoved (MouseEvent)
Mouse Button MouseListener mousePressed (MouseEvent)
mouseReleased (MouseEvent)
mouseEntered (MouseEvent)
mouseExited (MouseEvent)
mouseClicked (MouseEvent)
Key KeyListener keyPressed (KeyEvent)
keyReleased (KeyEvent)
keyTyped (KeyEvent)
Event Categories & API (2/2)
Category of Interface Name Functions
Event
Adjustment AdjustmentListener adjustmentValueChanged (AdjustmentEve
nt)
Window WindowListener windowClosing (WindowEvent)
windowOpened (WindowEvent)
windowIconified (WindowEvent)
windowDeiconified (WindowEvent)
windowClosed (WindowEvent)
windowActivated (WindowEvent)
windowDeactivated (WindowEvent)
Text TextListener textValueChanged (TextEvent)
Event Adaptor
• Every listener interface has a corresponding adapt
er class
• Also an event handler but all functions are already
defined
public class MouseMotionAdapter implements MouseMotionListener {
public void mouseDragged (MouseEvent e) {}
public void mouseMoved (MouseEvent e) {}
}
• To use an event adapter
public class MouseMotionAd extends MouseMotionAdapter {
• Simplifies coding
• Due to single-inheritance of Java, Applet cannot use Ev
ent adapter
Mouse Adaptor (1/2)
import java.awt.*;
import java.awt.event.*;

public class MouseMotionAd extends MouseMotionAdapter {

static TextField tf;

public static void main(String args[]) {


Frame f;

f = new Frame("MouseMotionAdapter example");


f.add(new Label ("Click and drag the mouse"),
BorderLayout.NORTH);
tf = new TextField (30);
f.add (tf, BorderLayout.SOUTH);
f.addMouseMotionListener(new MouseMotionAd());
f.setSize(300, 200);
f.setVisible(true);
}
Mouse Adaptor (2/2)
public void mouseDragged (MouseEvent e) {
String s =
"Mouse dragging: X = " + e.getX() +
" Y = " + e.getY();
tf.setText (s);
}
//
// No need to override the unused functions
// since MouseMotionAdapter is a class, not an interface
// public void mouseMoved (MouseEvent e) { }
//
}
---- Section Break ----

Anonymous Inner Class
• A way of coding event handler
• Further simplifies the coding
• Following example uses two anonymous inner
classes for event handling
Anonymous.java (1/2)
import java.awt.*;
import java.awt.event.*;

public class Anonymous {


static TextField tf;
public static void main(String args[]) {
Frame f;
f = new Frame("MouseMotionAdapter example");
f.add(new Label ("Click and drag the mouse"),
BorderLayout.NORTH);
tf = new TextField (30);
f.add (tf, BorderLayout.SOUTH);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Anonymous.java (2/2)
f.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged (MouseEvent e) {
String s = "Mouse dragging: X = " ;
s += e.getX() + " Y = " + e.getY();
tf.setText (s);
}
});

f.setSize(300, 200);
f.setVisible(true);
}
}
Adaptor Highlights
• No need to subclass from WindowAdapter class in the cl
ass header
• The handler class, actually a subclass of WindowAdapte
r is defined; its function is overridden; and the class is ins
tantiated. ALL done at the same time

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Adaptor Highlights (cont’)
• Since the newly defined subclass has no name,
and it is defined within a function, this type of
class is known as
– Anonymous Inner Class
---- Section Break ----

TextField & TextArea
import java.awt.*;
import java.applet.*;

public class Text extends Applet {


public void init() {
TextArea textarea = new TextArea(
"This text area has 3 rows and 40 columns", 3, 40);
TextField textfield = new TextField(
"This text field has 30 columns", 30);
add(textarea);
add(textfield);
}
}
Fonts
• Create the Font object
– Font f = new Font (“Family name”, Style, Size);
– Family Name (String):
» Dialog, DialogInput, Monospaced, Serif, SansSerif, or S
ymbol
– Style (int)
• Font.BOLD, Font.PLAIN, Font.ITALIC, or
• Font.BOLD + Font.ITALIC
– Size (int)
• Font size
• Use the Font object
– g.setFont(f);
Font1.java (1/2)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Font1 extends Applet implements ActionListener {


TextField textField;

public void init() {


textField = new TextField(10);
add(textField);
textField.setText("32");
textField.addActionListener(this);
}

public void paint(Graphics g) {


String s = textField.getText();
int size = Integer.parseInt(s);
Font1.java (2/2)
Font font = new Font("TimesRoman", Font.PLAIN, size);
g.setFont(font);

FontMetrics fontMetrics = g.getFontMetrics(font);


int height = fontMetrics.getHeight();

int row = 80;


g.drawString("This is the first line.", 70, row);
row += height;
g.drawString("This is the second line.", 70, row);
row += height;
g.drawString("This is the third line.", 70, row);
row += height;
g.drawString("This is the fourth line.", 70, row);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
Font1 Applet
---- Section Break ----

Checkbox1.java (1/2)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Checkbox1 extends Applet implements ItemListener {


private Checkbox one, two, three;
private Panel boxPanel;
private TextField textField;

public void init() {


one = new Checkbox("One", true);
two = new Checkbox("Two", false);
three = new Checkbox("Three", false);

one.addItemListener(this);
two.addItemListener(this);
three.addItemListener(this);
Checkbox1.java (2/2)
setLayout(new BorderLayout());
boxPanel = new Panel();
textField = new TextField(20);
add(boxPanel, BorderLayout.CENTER);
add(textField, BorderLayout.NORTH);

boxPanel.add(one);
boxPanel.add(two);
boxPanel.add(three);
}

public void itemStateChanged(ItemEvent ev) {


String state = "deselected";
if (ev.getStateChange() == ItemEvent.SELECTED) {
state = "selected";
}
textField.setText(ev.getItem() + " " + state);
}
}
Checkbox1 Applet
---- Section Break ----

Choice1.java (1/3)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Choice1 extends Applet implements ItemListener {


Choice menu;
Color color;

public void init() {


Choice menu = new Choice();
menu.addItem("Black");
menu.addItem("Red");
menu.addItem("Green");
menu.addItem("Blue");
menu.addItemListener(this);

add(menu);
color = Color.black;
}
Choice1.java (2/3)
public void paint(Graphics g){
Font font = new Font("TimesRoman", Font.BOLD, 24);
int height = font.getSize();
g.setFont(font);

g.setColor(color);

g.drawString("This text is drawn in", 32, 75);


g.drawString("the color selected from", 32, 75+height);
g.drawString("the above choice menu.", 32, 75+2*height);
}

public void itemStateChanged(ItemEvent e) {


handleMenu((String)e.getItem());
}
Choice1.java (3/3)
private void handleMenu(String item) {
if (item == "Black")
color = Color.black;
else if (item == "Red")
color = Color.red;
else if (item == "Green")
color = Color.green;
else
color = Color.blue;

repaint();
}
}
---- Section Break ----

ScrollBar1.java (1/2)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class ScrollBar1 extends Applet implements AdjustmentListener {


Scrollbar scrollbar;
String s;

public void init() {


BorderLayout layout = new BorderLayout();
setLayout(layout);

scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 50, 0, 1, 100);


scrollbar.addAdjustmentListener(this);
add(scrollbar, BorderLayout.NORTH);

s = "50";
Font font = new Font("TimesRoman", Font.BOLD, 72);
setFont(font);
}
ScrollBar1.java (2/2)

public void paint(Graphics g) {


g.drawString(s, 60, 120);
}

public void adjustmentValueChanged(AdjustmentEvent e) {


s = String.valueOf(e.getValue());
repaint();
}
}
---- Section Break ----

Menu Class Hierarchy

O b je c t

M enuC om ponent

M enuBar M e n u IT e m

M enu C h e c k b o x M e n u Ite m
MenuBar1.java (1/5)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MenuBar1 extends Applet implements ActionListener {


MenuFrame frame;
Button button;

public void init() {


frame = new MenuFrame("MenuFrame Window");
frame.setLocation(200,0);

button = new Button("Show Window");


button.addActionListener(this);
add(button);
}
MenuBar1.java (2/5)
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Hide Window")) {
frame.hide();
button.setLabel("Show Window");
} else {
frame.show();
button.setLabel("Hide Window");
}
}
}
MenuBar1.java (3/5)
class MenuFrame extends Frame implements ActionListener, ItemListener {
MenuBar menuBar;
String str = "";

MenuFrame(String title) {
super(title);
menuBar = new MenuBar();
setMenuBar(menuBar);

Menu menu = new Menu("Test");


menuBar.add(menu);

MenuItem item = new MenuItem("Command 1");


item.addActionListener(this);
menu.add(item);
MenuBar1.java (4/5)
item = new MenuItem("Command 2");
item.addActionListener(this);
menu.add(item);

menu.addSeparator();

CheckboxMenuItem checkItem = new CheckboxMenuItem("Check");


checkItem.addItemListener(this);
menu.add(checkItem);

Font font = new Font("TimesRoman", Font.BOLD, 20);


setFont(font);
setSize(200, 200);
}

public void paint(Graphics g) {


g.drawString(str, 20, 100);
}
MenuBar1.java (5/5)
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Command 1")
str = "You selected Command 1";
else
str = "You selected Command 2";
repaint();
}

public void itemStateChanged(ItemEvent e) {


if (e.getStateChange() == ItemEvent.SELECTED)
str = "You selected " + e.getItem();
else
str = "You deselected " + e.getItem();
repaint();
}
}
MenuBar1 Applet
MenuBar Exercise
• Create a Java application GUI.java with the following
components
• Implements only the window closing function and the
quit menu
• A partially completed program is put in the test folder
---- Section Break ----

Graphics in Java
• The Graphics object has a lot of useful methods
for drawing various graphic effects
• This section introduces some of its interesting
methods
Sample: MyDraw
• Allows user to do free-hand sketch on the applet
• The g.drawLine() method is used
• The g.drawLine() method is not called by paint() m
ethod, but by mouseDragged() method
• Therefore we have to explicitly obtain the Graphics
object via getGraphics() inside init()
MyDraw.java (1/3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class MyDraw extends Applet


implements MouseListener, MouseMotionListener {

int XOld, YOld, XNew, YNew;


Graphics g;

public void init() {


g = getGraphics();
addMouseListener(this);
addMouseMotionListener(this);
}

public void paint(Graphics g) {


g.drawRect(10,10,230,230);
}
MyDraw.java (2/3)
public void mousePressed(MouseEvent e) {
XOld = e.getX();
YOld = e.getY();
}

public void mouseDragged(MouseEvent e) {


XNew = e.getX();
YNew = e.getY();
g.drawLine (XOld, YOld, XNew, YNew);
XOld = XNew;
YOld = YNew;
}

//Try commenting the last 2 assignment statements an


d see the result!
MyDraw.java (3/3)
// The other, unused methods of the MouseListener interface.
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// The other method of the MouseMotionListener interface.


public void mouseMoved(MouseEvent e) {}
}
Explain MyDraw (I)

public void mousePressed(MouseEvent e) {


XOld = e.getX();
YOld = e.getY();
}

- when the mouse button is clicked, the current


position is placed in the Old variables, preparing
for the starting point in subsequent drawing invo
ked in mouseDragged() method
Explain MyDraw (II)
mouseDragged(MouseEvent e) { ... };
- another automatic method invoked if the drag
action is applied to the mouse
mouseDragged(MouseEvent e) {
XNew = e.getX();
YNew = e.getY();
...
- current position is assigned to the New variables,
preparing for the ending point of the line drawn
Explain MyDraw (III)
g.drawLine(XOld, YOld, XNew, YNew);

- to draw a line from the point when the mouse


click event occurs to the point where the drag
event ends
MyDraw1.java (1/3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class MyDraw1 extends Applet


implements MouseListener MouseMotionListener {

int XOld, YOld, XNew, YNew;


Graphics g;

public void init() {


g = getGraphics();
addMouseListener(this);
addMouseMotionListener(this);
}

public void paint(Graphics g) {


g.drawRect(10,10,230,230);
}
MyDraw1.java (2/3)
public void mousePressed(MouseEvent e) {
XOld = e.getX();
YOld = e.getY();
}

public void mouseDragged(MouseEvent e) {


XNew = e.getX();
YNew = e.getY();
g.drawArc(XOld, YOld, 25, 25, 0, 90);
XOld = XNew;
YOld = YNew;
}
MyDraw1.java (3/3)
// The other, unused methods of the MouseListener interface.
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// The other method of the MouseMotionListener interface.


public void mouseMoved(MouseEvent e) {}
}
Explain MyDraw1
g.drawArc(XOld, YOld, 25, 25, 0, 90);
- an arc is contained in an invisible rectangle with
upper left corner specified by the 1st and 2nd
parameters (i.e. XOld and YOld) and width and
height specified by the 3rd and 4th parameters
(i.e. 25 and 25)
- 5th parameter : 0 means the arc starts from 0
degree
- 6th pararmeter : 90 means the arc ends at 90
degrees, positive => the locus is in anti-clockwise
direction
MyDraw2.java
….

public void mouseDragged(MouseEvent e) {


XNew = e.getX();
YNew = e.getY();
g.drawArc(XOld, YOld, 25, 25, 0, 360);
XOld = XNew;
YOld = YNew;
}

….
MyDraw3.java
….

public void mouseDragged(MouseEvent e) {


XNew = e.getX();
YNew = e.getY();
g.fillArc(XOld, YOld, 15, 15, 0, 360);
XOld = XNew;
YOld = YNew;
}

….
MyDraw4.java
….

public void mouseDragged(MouseEvent e) {


XNew = e.getX();
YNew = e.getY();
g.setColor(Color.red);
g.fillArc(XOld, YOld, 15, 15, 0, 360);
XOld = XNew;
YOld = YNew;
}

….
Show GIF when Dragging
Expected effects :

A file undercon.gif is stored in the subdirectory


already.

When dragging the mouse, we would like to see the


gif file displayed along the way.
MyDraw5.java (1/3)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class MyDraw5 extends Applet


implements MouseListener, MouseMotionListener {

int XOld, YOld, XNew, YNew;


Graphics g;
Image myImage;

public void init() {


g = getGraphics();
myImage = getImage(getCodeBase(), "undercon.gif");
addMouseListener(this);
addMouseMotionListener(this);
}

public void paint(Graphics g) {


g.drawRect(10,10,230,230);
}
MyDraw5.java (2/3)
public void mousePressed(MouseEvent e) {
XOld = e.getX();
YOld = e.getY();
}

public void mouseDragged(MouseEvent e) {


XNew = e.getX();
YNew = e.getY();
g.drawImage(myImage, XOld, YOld, this);
XOld = XNew;
YOld = YNew;
}
MyDraw5.java (3/3)
// The other, unused methods of the MouseListener interface.
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// The other method of the MouseMotionListener interface.


public void mouseMoved(MouseEvent e) {}
}
Explain MyDraw5 (I)
Image myImage;
- defines MyImage as Image variable

myImage=getImage(getCodeBase(),"undercon.gif");

- getCodeBase() gets the path position of


MyDraw5.class
- undercon.gif should be placed in the same path as
MyDraw5.class
- getImage() method gets the image and stores it in
the variable MyImage
Explain MyDraw5 (II)
g.drawImage(myImage, XOld, YOld, this);
- Parameters :
* 1st (myImage) : image to be displayed
* 2nd and 3rd (XOld and YOld) : upper left corner
of coordinate
* 4th (this) : Image Observer object
MyDraw6.java

public void mouseDragged(MouseEvent e) {


XNew = e.getX();
YNew = e.getY();
g.drawImage(myImage, XOld, YOld, 150, 150, this);
XOld = XNew;
YOld = YNew;
}


Explain MyDraw6
g.drawImage(myImage, XOld, YOld, 150, 150, null);
- note that this time drawImage() method has 6
parameters instead of 4
- Java can provides methods with same names but
different no. of parameters and this technique is
called Method Overloading
- the additional parameters (3rd and 4th) 150, 150
specify the width and height of the new image
respectively
Commonly Used Graphics API
drawArc() Draws a hollow arc
drawLine() Draws a straight line
drawOval() Draws a hollow oval
drawPolygon() Draws a hollow polygon
drawRect() Draws a hollow rectangle
drawRoundRect() Draws a hollow rectangle with rounded corners
drawString() Displays a text string
setColor() Sets the drawing color
setFont() Sets the font

fillArc(), fillOval(), fillPolygon(), fillRect(), fillRoundRect() are methods


to draw filled shapes
---- Section Break ----

Multi-Thread Programming
• A modern OS supports multi-tasking
– several programs can run simultaneously in the OS

• Java support multi-tasking within a single


program
– Java program can have several sub-programs
running concurrently within the main program
– Achieve a higher level of concurrency
– Known as multi-threading
Multi-Thread Applications
• Issue several parallel SQL queries to several dat
abases
• An applet with several animations running simult
aneously
• A single Java servlet instance on the web server
supports multiple requests from many different b
rowsers
• more…
Java’s Strength
• If the underlying OS supports native multi-
threading, JVM can leverage on the native
support
• Even if the OS does not support multi-threading,
JVM can still simulate the multi-threading
environment
• In the other words, JVM always supports multi-
threading irrespective of the underlying platform
Multi-Thread Animation
• What’s Animation?
• a series of images shown fast enough to create
the moving perception for human beings
• General algorithm :
// Animation starts here
A statement that displays image #1
A statement that displays image #2
A statement that displays image #3
...
// Animation ends here
What’s Animation (cont’)
• however, today's computer is too fast
• Add some delays between frames :
• // Animation starts here
• A statement that displays image #1
• delay (so that image #1 stays on the screen
for the duration of the delay)
• A statement that displays image #2
• delay (so that image #2 stays on the screen
for the duration of the delay)
• ...
• // Animation ends here
MyCounterWoMT.java (1/2)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MyCounterWoMT extends Applet implements ActionListener {

TextField textField;
int num = 0;

public void init() {


textField = new TextField(20);
add(textField);
textField.addActionListener(this);
}
MyCounterWoMT.java (2/2)
public void paint(Graphics g) {
String s = textField.getText();
g.drawString(s, 40, 50);
while (true) {
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {}

g.drawString ("My Counter: " + num, 40, 70);


if (num++ == 1000)
num = 0;
}
}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
The Problem
• Can you enter anything into the text field?
• No, because the main logic in being held by the
animation loop
• What we want are
– User can use the text field to enter something
– Animation happens at the same time
Reasons
• the algorithms described are "linear"
• if the animation lasts for say 10 minutes, the user
• will have to stay for the whole duration to watch
the animation, while at the same time doing
nothing on the computer system
• this eliminates at least the possibilities of
background animations
• to solve this, we have to use Java's threading
capabilities - the program level of multitasking

Multi-Threading is the solution!


MyCounterWMT.java (1/3)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MyCounterWMT extends Applet implements ActionListener, R


unnable {

TextField textField;
int num = 0;
Thread myThread;

public void init() {


textField = new TextField(20);
add(textField);
textField.addActionListener(this);
}
MyCounterWMT.java (2/3)
public void paint(Graphics g) {
String s = textField.getText();
g.drawString(s, 40, 50);

g.drawString ("MyCounter " + num, 40, 70);


if ( num++ == 1000 )
num = 0;
}

public void start() {


myThread = new Thread(this);
myThread.start();
}
MyCounterWMT.java (3/3)
public void stop() {
myThread.stop();
}

public void run() {


while (true) {
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {}
repaint();
}
}

public void actionPerformed(ActionEvent e) {


repaint();
}
}
Multi-Thread Programming Steps
1. Define a class with a run() method & implements Runnable interface :

public class Abc implements Runnable {


....
public void run() {
// interesting stuff here
}
}

2. In the class you want to use a thread :

public class Xyz {


....
Abc a = new Abc(); // the runnable object called a
Thread t = new Thread(a); // use the runnable object to construct a thread
t.start(); // starts the thread and invokes the run() method
....
}
MyCounter.java (1/2)
import java.applet.*;
import java.awt.*;

public class MyCounter extends Applet implements Runnable {

Thread myThread;
int num = 0;

public void paint(Graphics g) {


g.drawString ("MyCounter " + num, 10, 20);
if ( num++ == 1000 )
num = 0;
}

public void start() {


myThread = new Thread(this);
myThread.start();
}
MyCounter.java (2/2)

public void stop() {


myThread.stop();
}

public void run() {


while (true) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {}
repaint();
}
}
}
Explain MyCounter (I)
public class MyCounter extend Applet implements
Runnable { .... }
- implements an applet in a Java thread

Thread myThread
- defines myThread as a Thread variable
Explain MyCounter (II)
public void start() {
myThread = new Thread(this);
myThread.start();
}

- start() method is called automatically when the


applet is started
- myThread = new Thread(this);
* a new thread is created
- myThread.start();
* starts the newly created thread myThread
Explain MyCounter (III)
public void stop() {
myThread.stop();
}

- stop() method will be called automatically when an


applet is closed
- myThread.stop() will stop the thread myThread
Explain MyCounter (IV)
public void run() { ... }
- when the thread is started, the run() method will
be run automatically
- the heart of animation should be coded here
- in particular, it consists of :
* the non-active part : sleep() method
* the active part : some other methods e.g. paint()
Explain MyCounter (V)
Thread.currentThread().sleep(10);
- sleep(n) : n is in units of milliseconds
- for graphics animation, n should be set to 400 to
1000

repaint();
- when MyThread applet is not silent, it will perform
repaint() method
- in general, other methods can be performed in
addition to repaint() method
Explain MyCounter (VI)
- Summary:
To implement a Runnable Applet, we have to :
1. write start() method
2. write stop() method
3. write run() method
4. in run() method, write 2 tailored-made
components :
4.1 inactive part : sleep() method
4.2 active part : methods to be performed
when the applet awakes
Explain MyCounter (VII)
public void paint(Graphics g) { ... }
- invoked when the repaint() method is called

if (num++ == 1000) {
num = 0;
}
- the counter num will be reset to 0 when it
reaches 1000
HTML Parameter for Applet
<html>
<title>MyCounter1.html</title>
<body>
<h1>This is the MyCounter1.html</h1>

<applet code="MyCounter1.class" width=200 height=200>


<param name=sleepValue Value="1000">
</applet>

<hr>
This HTML page uses the MyCounter1.class applet
<hr>
<body>
</html>
MyCounter1.java (1/2)
import java.applet.*;
import java.awt.*;
public class MyCounter1 extends Applet implements Runnable {

Thread myThread;
int num, sleepValue;

public void init() {


sleepValue = Integer.parseInt (getParameter(“sleepValue”));
}

public void paint(Graphics g) {


g.drawString (“Sleep Value: "+ sleepValue +
" Counter: “ + num, 10, 20);
if ( num++ == 1000 )
num = 0;
}
MyCounter1.java (2/2)
public void start() {
myThread = new Thread(this);
myThread.start();
}

public void stop() {


myThread.stop();
}

public void run() {


while (true) {
try {
Thread.currentThread().sleep (sleepValue);
} catch (InterruptedException e) {}
repaint();
}
}
}
Explain MyCounter1
sleepValue = Integer.parseInt (getParameter(“sleepValue”));

- to get value from Value corresponds to sleepValue as specified in


<param name=sleepValue Value="1000"> in HTML

- to transform String value to integer value


---- Section Break ----

• Java
Package java.util

• Relieve the Java Programmers from some


common but complicated tasks
• Vector class
• Date class
• Random class
Vector – Alternative to Array

• Vector is an alternative to Array


• Better control over Vector
MyAnim2.java (1/3)
import java.applet.*;
import java.awt.*;
import java.util.*;

public class MyAnim2 extends Applet implements Runnable {


Thread myThread;
Vector theImages = new Vector(2);
int frameNo = 0;

public void init() {


Image tempImage;
for (int i=1; i<3; i++) {
tempImage=getImage(getCodeBase(), "T“ + i +“.gif");
theImages.addElement(tempImage);
}
}
MyAnim2.java (2/3)
public void paint(Graphics g) {
Image currentImage = (Image)theImages.elementAt(frameNo);
g.drawImage(currentImage, 30, 70, this);
if ( ++frameNo == 2 )
frameNo = 0;
}

public void start() {


myThread = new Thread(this);
myThread.start();
}

public void stop() {


myThread.stop();
}
MyAnim2.java (3/3)

public void run() {


while (true) {
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {}
repaint();
}
}
}
Explain MyAnim2 (I)
Vector theImages=new Vector(2);
- in Java, vector is similar to one-dimensional array
- Vector(2) means create an Vector object with initial size equals to two

for (int i=1; i<3; i++) {


tempImage=getImage(getCodeBase(), "T“ + i +“.gif");
theImages.addElement(tempImage);
}

- in the loop, tempImage will be set to T1.gif and T2.gif as i propagates


- addElement() method is used to add elements (i.e. T1.gif and T2.gif)
into the vector theImages
Explain MyAnim2 (II)
currentImage = (Image)theImages.elementAt(frameNo);

- elementAt() method returns vector element, but we are not sure what
is the data type of it
- (image) : casting technique to cast the returned value to Image type
- the returned casted image is then stored in currentImage
Date1.java

access and manipulate dates and times
import java.util.*;

public class Date1 {


public static void main (String args[]) {
Date today = new Date();
System.out.println("Today is " + today);

//Date birthday = new Date(102, 5, 28, 0, 0, 00);

Calendar cal = new GregorianCalendar(2002, Calendar.MAY, 30);


Date birthday = cal.getTime();
System.out.println("His birthday is " + birthday.toString());
}
}
Random1.java
import java.lang.Math;
import java.util.Date;
import java.util.Random;

class Random1 {
public static void main(String args[]) throws java.io.IOException {
int count=6;
Random randGen = new Random();
System.out.println("Uniform Random Integers");
for (int i=0; i<count; i++)
System.out.println(randGen.nextInt());
System.out.println("\n");

System.out.println("Uniform Random Integers [1,6]");


for (int i=0; i<count; i++)
System.out.println(Math.abs(randGen.nextInt())%6+1);
}
}
TheWanderer.java (1/2)
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;

public class TheWanderer extends Applet implements ActionListener{


int xpos = 100;
int ypos = 100;
Button b = new Button("Click me!");
Random random;

public void init() {


b.addActionListener(this);
add(b);
int seed = (int)(new Date()).getTime();
random = new Random(seed);
}
TheWanderer.java (2/2)
public void paint(Graphics g) {
g.setColor(Color.cyan);
g.fillOval(xpos,ypos,50,50);
}

public void actionPerformed(ActionEvent e) {


xpos += (Math.abs(random.nextInt())%10-7);
ypos += (Math.abs(random.nextInt())%10-7);
repaint();
}
}
---- Section Break ----

• Java
Package java.net

• Web interface classes


• URL and URLConnection classes
• provide a quick and easy way to access content
using URL
• Raw network interface classes
• support for socket programming
• building blocks for implementing new protocols
• Extension classes
• for extending capabilities of the URL class
GetURLInfo.java (1/2)
import java.net.*;
import java.io.*;
import java.util.*;

public class GetURLInfo {

public static void main(String[] args) throws


MalformedURLException,
IOException {

URL url = new URL(args[0]);


URLConnection connection = url.openConnection();
printinfo(connection);
}
GetURLInfo.java (2/2)
public static void printinfo(URLConnection u) throws IOException {

System.out.println(u.getURL().toExternalForm() + ":");
System.out.println(" Content Type: " + u.getContentType());
System.out.println(" Content Length: " + u.getContentLength());
System.out.println(" Last Modified: " + new Date(u.getLastModified()));
System.out.println(" Expiration: " + u.getExpiration());
System.out.println(" Content Encoding: " + u.getContentEncoding());
System.out.println("First five lines:");
DataInputStream in = new DataInputStream(u.getInputStream());

for(int i = 0; i < 5; i++) {


String line = in.readLine();
if (line == null) break;
System.out.println(" " + line);
}
}
}
Connect1.java (1/3)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;

public class Connect1 extends Applet implements ActionListener {


TextField textField;
boolean badURL;

public void init() {


textField = new TextField("", 40);
Button button = new Button("Connect");
button.addActionListener(this);

add(textField);
add(button);

badURL = false;
}
Connect1.java (2/3)
public void paint(Graphics g) {
Font font = new Font("TimesRoman", Font.PLAIN, 24);
g.setFont(font);

int height = font.getSize();

if (badURL)
g.drawString("Bad URL!", 60, 130);
else
{
g.drawString("Type the URL to which", 25, 130);
g.drawString("you want to connect,", 25, 130+height);
g.drawString("and then click the Connect", 25, 130+height*2);
g.drawString("button.", 25, 130 + height*3);
}
}
Connect1.java (3/3)
public void actionPerformed(ActionEvent e) {
String str = textField.getText();

try {
URL url = new URL(str);
AppletContext context = getAppletContext();
context.showDocument(url);
} catch (MalformedURLException e1) {
badURL = true;
repaint();
}
}
}
---- Section Break ----


Java Reference Books
1. Java in a Nutshell by Flanagan published by O'Reilly
2. Java Unleashed by Morrison, et al. published by Sa
ms Net

3. Hooked On Java by Hoff, Shaio and Starbuck publis


hed by Addison Wesley
4. Thinking In Java by Bruce Eckel published by Prenti
ce Hall

5. The Java Programming Language 3rd Edition by Ja


mes Gosling published by Addison Wesley
---- Section Break ----

• Java
Intro To Multimedia

• Java
Multimedia & Java

• Java

You might also like