Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 416

Java Programming

Daher Thabit Daher


Chief Architect
E-mail: daher@rss.gov.jo
Contents
 Getting Started
 Variables, Data Types, Operators, & Expressions
 Objects Data Structure
 Inheritance & Polymorphism
 Exceptions
 Java Database Connectivity (JDBC)
 Threading
 Java Applets
 I/O Streams
What is Java ?
• Primarily, Java is a programming language,
an object-oriented language developed at
Sun Microsystems.
Some History
• In 1991, Sun Microsystems set up a research
project to develop a language for
programming ‘intelligent’ consumer
electronics
– e.g. video recorders, TVs
• The language was called Oak (later changed
to Java). Developed by James Gosling, and
others.
• August 1993: the project was cancelled.
• The Web became popular during 1993.

• July 1994: Sun restarted work on Java as a


Web programming language
– Java contains networking features, platform
portability, and a small runtime system
• Java released May 1995
– Netscape supported Java in Navigator 2.0,
• May 1996: JDK v.1.0 released.

continued
• February 1997: JDK v.1.1 released
– major changes in the event model used by the GUI;
inner classes introduced

• December 1998: JDK v.1.2 released


– also known as Java 2
– much improved GUIs (SWING), graphics

• September 2000: JSDK v.1.3 released


– improved networking, sound, security
– see http://java.sun.com/j2se/1.3/
docs/relnotes/features.html
Java, JDK, JSDK, JRE
• There are several 'Java' names:
– Java is the name of the language
– JDK is the old name for JSDK
– JSDK = "Java Software Development Kit"
• JSDK 1.3
• JSDK 1.4 is available now (October 2001)

continued
• JSDK contains all the libraries (packages),
compiler, and other tools for
writing/running/debugging Java code.

• JRE = "Java Runtime System"


– a cut-down version of JSDK with only the
packages/tools needed for running Java code
– most often used by Web browsers
JSDK Installation
• The current JSDK (v.1.3), its documentation,
and excellent tutorials are here at:
ftp://ftp.coe.psu.ac.th/pub/java/

• The filenames are: JSDK 1.3


– j2sdk1_3_0-win.exe for Windows
– j2sdk-1_3_0-update1-doc.zip
– sun-java-tutorial.zip

continued
Update Autoexec.bat
• Add the bin path for Java to the PATH
environment variable:
set PATH=%PATH%;c:\jdk1.3.0_02\bin

• This says where the Java tools (e.g. javac)


are located.
Why Java ?
 Simple  Garbage Collected
 Object-oriented  Portable
 Byte-code Interpreted  High-performance
 Secure
 Multithreaded
Java Advantages
• Productivity
– object orientation (reuse)
– standard, large libraries (packages)
– Java Beans (component model)

• Simpler/safer than C, C++


– no pointer arithmetic, automatic garbage
collection, array bounds checking, etc.

continued
• GUI features
– the event model
– the SWING and Abstract Windowing Toolkit
(AWT) packages

• Multimedia
– graphics, animations, audio, video, etc.
• Network support
– communication with other machines/apps
– variety and standards:
• sockets, RMI, CORBA
• Multithreading / concurrency
– can run several ‘threads’ at once

continued
• Portablility / Platform Independence
– “write once; run anywhere”

continued
• Supports native code
– can integrate legacy code
• Java Development Kit (JDK) is free
• Good programming environments
– Visual Age ,Symantec Visual Cafe, Borland’s
Jbuilder,Forte for Java,WSAD4.0-5.0
– do not use them when first learning Java
• Good for teaching computing
– many important ideas in one place
• It’s new!

continued
Java Disadvantages
• Java’s security restrictions makes some
code hard to write:
– cannot “see” much of a local machine
• Slow Internet connections
– makes it difficult to download medium/large
applets
• Lots to learn
– Java language (small) and Java libraries
(very large)
Writing Java code
• There are two kinds of Java program:
– Java applications
• ordinary programs; standalone
– Java applets
 run in a browser (or appletviewer)
 attached to Web pages, so can be downloaded
easily from anywhere
 applets have access to browser features
Java Bytecodes
• The Java compiler (javac) generates
bytecodes
– a set of instructions similar to machine code
– not specific to any machine architecture

• A class file (holding bytecodes) can be run


on any machine which has a Java runtime
environment.
The Bytecode Advantage
Java runtime
(Pentium)
javac (Pentium)

Java runtime
(Mac)
javac (Mac)
Java code Java bytecode
(.java file) (.class file)
Java runtime
javac (UNIX) (UNIX)
The Java Platform
 The Java Virtual Machine (Java VM)
 The Java Application Programming Interface
(Java API)
Java Program Structure
• Basic syntax of a Java class:
<modifier> class <name>
{
<attribute_declaration>
<constractor_declaration>
<method_declaration>
}
HelloWorld.java
class HelloWorld {
public static void main (String args [])
{
System.out.println (“Hello World “);
}
}
Declaring Attributes
<modifier> <type> <name> [=<default_value>];
type:byte-short-int-long-char-float-double,boolean .
• Examples:
Public class DeclarAttribute {
public int x;
private float y =1000.0;
private String name =“Daher Thabit”;
}
Declaring Methods
<modifier> <return_type> <name>(<parameter>){
statements;
}
Parameter : (parameter_type parameter_name)
Examples:
public class Thing {
private int x;
public int getX(){
return x;
}
public void setX(int new_x){
x = new_x;
}}
Access Control
Modifier Same class Same Package Subclass Universe

public Yes Yes Yes Yes

protected Yes Yes Yes

default Yes Yes

private Yes

• Variables and methods can be at one of four access levels:


public, protected,default,or private.
• Classes can be at the public or default.
Comments
• Comments in a program are also called
inline documentation
• They should be included to explain the
purpose of the program and describe
processing steps
• Java comments can take two forms:
// comment runs to the end of the line
/* comment runs to terminating
symbol, even across line breaks */
The Java API
The Java Application Programmer Interface (API)
is a collection of classes that can be used as needed

• The println and print methods are part of the Java


API; they are not part of the Java language itself
Both methods print information to the screen; the
difference is that println moves to the next line
when done,but print does not .
Class Libraries
• The Java API is a class library, a group of classes
that support program development
• Classes in a class hierarchy are often related by
inheritance
• The classes in the Java API is separated into
packages
• The System class, for example, is in package
java.lang
• Each package contains a set of classes that relate
in some way
Import Statment
• Basic syntax of the package statement:
Import <pkg_name>.<sub_pkg_name>.<class_name>;
Examples:
import java.util.list;
import java.io.*;
import java.sql.*;
The Java API Packages
• Some packages in the Java API:

java.applet java.net
java.awt java.rmi
java.beans java.security
java.io java.sql
java.lang java.text
java.math java.util
String Concatenation and
Addition
• The + operator serves two purposes
• When applied to two strings, they are combined
into one (string concatenation)
• When applied to a string and some other value
(like a number), that value is converted to a string
and they are concatenated
• When applied to two numeric types, they are
added together arithmetically
Command Line Arguments
• Names.java
• The main method accepts extra information on
the command line when a program is executed
> java Names Daher
• Each extra value is called command line argument
• In Java, command line arguments are always read
as a list of character strings
Variables
Variable (Way)
• Primitive type
(byte,short,int,long,char,float,double,boolean)
• Reference type (String,array,…..)
Variable (Place)
• inside a method (local)
• outside a method –member variable (global)
Data Types
Type Size/Format Description
integral
byte 8-bit two's complement Byte-length integer

short 16-bit two's complement Short integer

int 32-bit two's complement Integer

long 64-bit two's complement Long integer


Floating(real numbers)
Single-precision floating
float 32-bit point
Double-precision floating
double 64-bit point
(other types)
16-bit Unicode
char character A single character
A boolean value (true or
boolean true or false false)
Data Types: Examples
public static void main (String args[])
{
int count;
String title;
boolean isAsleep;
...
}
You can give variables initial values:
int numShoes, mySize, myAge = 33;
String myName = ”ali”;
boolean amTired = true;
int a = 4, b = 5, c = 6;
Variables
• Variable Declaration
int myInteger;
• Variable Initialization
myInteger = 10;
int count = 0;
• Final Variables (constants)
final int aFinalVariable = 0;
Operators
• Unary operators, ex. ++
– prefix or postfix notation
operator operand or operand operator
• Binary operators, ex. =
– infix notation
operand1 operator operand2
• Tertiary operator ?:
– infix notation
expression ? Operand1 : operand2
The Conditional Operator
• Java has a conditional operator that evaluates a
boolean condition that determines which of two
expressions is evaluated
• The result of the chosen expression is the result of
the entire conditional operator
• Its syntax is:
condition ? expression1 : expression2
• If the condition is true, expression1 is evaluated;
if it is false, expression2 is evaluated
• It is similar to an if-else statement, except that it is
an expression that returns a value
38
Arithmetic Operators
O p e ra to r U se D e s c rip tio n
+ op1 + op2 Ad d s op1 an d op2
- op1 - op2 Su b stracts op2 from op1
* op1 * op2 Mu ltip lies op1 b y op2
/ op1 / op2 Divid es op1 b y op2
% op1 % op2 Com p u tes th e rem in d er of d ivid in g op1 b y op2
Prom otes op to int if it's a byte , short ,
+ +op or char
- -op Arith m etically n eg ates op
++ op++ In crem en ts op b y 1, evalu ates b efore
++ ++op In crem en ts op b y 1, evalu ates after
-- op-- Decrem en ts op b y 1, evalu ates b efore
-- --op Decrem en ts op b y 1, evalu ates after
The Increment and Decrement
Operators
• The increment and decrement operators can be
applied in prefix (before the variable) or postfix
(after the variable) form
• When used alone in a statement, the prefix and
postfix forms are basically equivalent. That is,
count++;
is equivalent to
++count;

40
Example
If count currently contains 45, then
total = count++;
assigns 45 to total and 46 to count

If count currently contains 45, then


total = ++count;
assigns the value 46 to both total and count
Relational Operators
O p e ra to r U se R e tu rn s true if …
> op1 > op2 op1 is g reater th an op2
>= op1 >= op2 op1 is g reater th an or eq u al to op2
< op1 < op2 op1 is less th an op2
<= op1 <= op2 op1 is less th an or eq u al to op2
== op1 == op2 op1 an d op2 are eq u al
!= op1 != op2 op1 an d op2 are n ot eq u al
instanceof op1 instanceof op2 op1 an d op2 are assig n m en t com p atib le
op1 an d op2 are b oth true,
&& op1 && op2 con d ition ally evalu ates op2
eith er op1 or op2 is true,
|| op1 || op2 con d ition ally evalu ates op2
! ! op op is false
op1 an d op2 are b oth true ,
& op1 & op2 evalu ates op1 an d op2
eith er op1 or op2 is true ,
| op1 | op2 evalu ates op1 an d op2
Bitwise Operators
O p erato r U se O p eratio n
>> op1 >> op2 Shifts bits of op1 right by distance op2
<< op1 << op2 Shifts bits of op1 left by distance op2
Shifts bits of op1 right by distance op2
>>> op1 >>> op2 (unsigned)
& op1 & op2 Performs a bitwise and
| op1 | op2 Performs the bitwise or
^ op1 ^ op2 Performs the bitwise xor
~ ~ op Performs the bitwise complement
Assignment Operators
O p e ra to r U se O p e ra tio n
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2
&/ op1 &= op2 op1 = op1 & op2
|/ op1 |= op2 op1 = op1 | op2
^= op1 ^= op2 op1 = op1 ^ op2
<<= op1 <<= op2 op1 = op1 << op2
>>= op1 >>= op2 op1 = op1 >> op2
>>>= op1 >>>= op2 op1 = op1 >>> op2
Assignment Operators
• There are many such assignment operators,
always written as op= , such as:

Operator Example Equivalent To

+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
45
Expressions
count++;
Order of evaluation may matter
x * y * z // Order is unimportant
x + y / 100 // Order is important here
Operator Precedence
Operator
Category Operators
postfix operators [] . (params ) expr ++ expr --
unary operators ++expr --expr +expr -expr ~ !
creation or cast new (type )expr
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
conditional ? :
= += -= *= /= %= ^= &= |= <<=
assignment >>= >>>=
Branching
• Same as in C:
– if()
– switch()
– conditional expression ? :
The if/else Statements
if (expression) {
statement(s)
}
if (response == OK) {
// code to perform OK action
} else {
// code to perform Cancel action
}

49
The switch Statement
• The syntax of the switch statement is:

switch (expression) {
case value1:
statement-list1
case value2:
statement-list2
case …
}
50
Looping
• Same as in C:
– while()
– for()
– do/while()
– break
– continue
The while Statement

while (expression) {
statement
}
• In addition to while loops, Java has two other
constructs used to perform repetition:

• the do statement
• the for statement
The do Statement
• The do statement has the following syntax:

do statement

statement
while (condition); true
condition

false

53
The for Statement
• The syntax of the for loop is
for (intialization; condition; increment)
statement;

which is equivalent to
initialization;
while (condition) {
statement;
increment;
}
54
Branching Statements

• The break statement


• The continue statement
• The return statement
Break out of a nested set of control
structures (e.g. while, for, switch).

55
Control.java
class Control {
public static void main (String args[]){
int I;
for (I=0;I<10;I++){
System.out.println(I + “in for”);
}
while (true){
I--;
if (I < 0)
break;
System.out.println(I + “in while”);
}
}}
Constructing objects with new
To instantiate an object in Java, use the
keyword new followed by a call to the
class's constructor.
create a new Car variable called c:
Car c = new Car();
class MyPoint { // declaring class MyPoint
int x; // declaring variables
int y;
// declaring methods
void display() {
System.out.println("x = " + x);
System.out.println("y = " + y);
}
void setData(int a, int b) {
x = a;
y = b;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
class Create {
public static void main(String args[]) {
MyPoint obj = new MyPoint(); // creating MyPoint class object

// invoking methods
obj.setData(10,20);
obj.display();
obj.setData(30,40);
System.out.println("Return val of getX : " + obj.getX());
System.out.println("Return val of getY : " + obj.getY());
}
}
Objects for Organizing Data
• As our programs get more sophisticated, we need
assistance organizing large amounts of data
• Chapter focuses on:
 array declaration and use
 arrays of objects
 parameters and arrays
 multidimensional arrays
 the Vector class
 additional techniques for managing strings
60
Arrays
• An array is an ordered list of values
• Each value has a numeric index
• An array of size N is indexed from zero to
N-1
• The following array of integers has a size of
10 and is indexed from 0 to 9

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

61
Arrays
• A particular value in an array is referenced using
the array name followed by the index in brackets
• For example, the expression
scores[4]
refers to the value 67 (which is the 5th value in the
array)
• That expression represents a place to store a
single integer, can be used wherever an integer
variable can
• For example, it can be assigned a value, printed,
used in a calculation
62
Declaring Arrays
• The scores array could be declared as follows:
int[] scores = new int[10];
• An initializer list can be used to instantiate and
initialize an array in one step
• The values are delimited by braces and separated by
commas
• Examples:
int[] units = {147, 323, 89, 933, 540,269, 97, 114, 298, 476};

char[] letter_grades = {'A', 'B', 'C','D','F'};

63
Array Declarations Revisited
• The brackets of the array type can be associated
with the element type or with the name of the array.
Therefore
float[] prices;
and
float prices[];
are essentially equivalent
• The first format is usually more readable

64
Arrays of Objects
• The elements of an array can be object references
• The declaration
String[] words = new String[25];
reserves space to store 25 references to String
objects
• It does NOT create the String objects them selves
• Each object stored in an array must be instantiated
separately
65
Multidimensional Arrays

66
Declaring, Allocating and
Initializing Two Dimensional Arrays
class FillArray {
public static void main (String args[]) {
int[][] matrix;
matrix = new int[4][5];
for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
matrix[row][col] = row+col;
}}
}}
67
The Vector Class
• An object of class Vector is similar to an array in
that it stores multiple values
• However, a vector
 only stores objects
 does not have the indexing syntax that arrays have

• Service methods are used to interact with a vector


• The Vector class is part of the java.util package

68
The Vector Class
• An important difference between an array and a
vector is that a vector can be thought of as a
dynamic, able to change its size as needed
• Each vector initially has a certain amount of
memory space reserved for storing elements
• If an element is added that doesn't fit in the
existing space, more room is automatically
acquired.

69
import java.util.*;
class MyVector {
public static void main(String args[]) {
Vector v = new Vector();

v.addElement("Hello"); // add as an element


v.addElement(new Integer(100));
int length = v.size(); // the number of elements which the vector has
for (int i = 0; i < length; i++) {
System.out.println(v.elementAt(i)); // extracts the elements from the vector
}
}
}
The String Class
Creating a String Object
Four different ways
(there are more).
String color = “blue”;

String s1;
s1 = new String(“hello ”);

char chs[] = {‘a’, ‘n’, ‘d’, ‘y’};


String s2 = new String(chs);

s1 = s1 + s2 + “ davison”;
// + is string concatenation
Comparing Strings
0 9 A Z a z
0 48 57 65 90 97 122

• s1.equals(s2)
– lexicographical comparison
– returns true if s1 and s2 contain the same text

• s1 == s2
– returns true if s1 and s2 refer to the same object

continued
• s1.compareTo(s2)
– returns 0 if s1 and s2 are equal
– returns < 0 if s1 < s2; > 0 if s1 > s2

• s1.startsWith(“text”)
– returns true if s1 starts with “text”

• s1.endsWith(“text”)
– returns true if s1 ends with “text”
Locating Things in Strings
for text analysis
• s1.indexOf(‘c’)
– returns index position of first ‘c’ in s1, otherwise -1

• s1.lastIndexOf(‘c’)
– returns index position of last ‘c’ in s1, otherwise -1

• Both of these can also take string arguments:


– s1.indexOf(“text”)
Extracting Substrings
• s1.substring(5)
– returns the substring starting at index position 5

• s1.substring(1, 4)
– returns substring between positions 1 and 3
Changing Strings
• s1.replace(‘a’, ‘d’)
– return a new string; replace every ‘a’ by ‘d’

• s1.toLowerCase()
– return a new string where every char has been
converted to lowercase

• s1.trim()
– return a new string where any white space before or
after the s1 text has been removed
Other String Methods
• The String class is in the java.lang package
– there are many more String methods!
– e.g. s.length()

• Look at the Java documentation for the String


class:
The StringTokeniser Class
• This class provides a way of separating a
string into tokens
– e.g. “hello Daher Thabit”
becomes three tokens:
“hello” “Daher” “Thabit”

• Very useful for parsing


– dividing a program into tokens representing
variables, constants, keywords, numbers, etc.
The Basic Technique
• A String is converted to StringTokenizer, and
then the tokens are removed one at a time
inside a loop:
String token:
StringTokenizer st =
new StringTokenizer(
“...the string ...”);
while ( st.hasMoreTokens() ) {
token = st.nextToken();
: // do something with token
}

continued
• StringTokenizer st =
new StringTokenizer(...)
– creates a sequence of tokens from the string
– the default separators are “\n\t\r”
(newline, tab, carriage return)
– the separators can be changed

• st.hasMoreTokens()
– test if there are any more tokens left

• st.nextToken()
– returns the next token as a String object
Constructors
 Constructors create new instances of a class,
that is objects.
 Constructors are special methods that have
the same name as their class and no return
type.
class MyPoint {
int x;
int y;

MyPoint() { // constructor with no argument


System.out.println("called MyPoint().");
x = 0;
y = 0;
}
MyPoint(int a, int b) { // constructor with two int value
arguments
System.out.println("called MyPoint(int, int).");
x = a;
y = b;
}
void display() {
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
class Constructor {
public static void main(String args[]) {
MyPoint obj = new MyPoint(); // executing the constructor with no
argument
obj.display();
System.out.println();

MyPoint obj2 = new MyPoint(10, 20);


// the constructor with two int value
arguments executed
obj2.display();
}
}
Overloading
Overloading is when the same method or
operator can be used on many different
types of data.
public void println(int i)
public void println(float f)
public void println()
class MyPoint {
int x;
int y;

// display() method with no parameter


void display() {
System.out.println("I don't have parameter.");
System.out.println("x = " + x);
System.out.println("y = " + y);
}
// display() method with two parameters
void display(int a, int b) {
x = a;
y = b;
System.out.println("I have two parameters.");
System.out.println("x = " + x);
System.out.println("y = " + y);
}
void setData(int a, int b) {
x = a;
y = b;
}
}
class Overload {
public static void main(String args[]) {
MyPoint obj = new MyPoint();

obj.setData(10,20);
obj.display(); // invoking display() method with no parameter
obj.display(30,40); // invoking display() method with two int value
parameters
}
}
Inheritance

When a class inheritrs from only one class,it


is called single inheritance.
<modifier> class <name>[extends <superclass>]
{
<declarations>
}
class MyPoint { // superclass MyPoint
private int x;
private int y;
public void setData(int a, int b) {
x = a;
y = b;
}
public void display() {
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
class Derived extends MyPoint { // subclass Derived
private int z;
public void setData2(int c) {
z = c;
}
public void display2() {
System.out.println("z = " + z);
}
}

class Inheri {
public static void main(String args[]){
Derived obj = new Derived();

obj.setData(10,20); // invoking a method of a superclass


obj.display();

obj.setData2(30); // invoking a method of a subclass


obj.display2();
}
}
Overriding
 A subclass can modify behavior inherited
from a parent class .
 A subclass can create a method with
defferent functionality than the parents
method but with the same:
 Name
 Return type
 Argument list
class MyPoint {
public void display() {
System.out.println("display() in MyPoint.");
}
}
class Derived extends MyPoint {
// overriding display() method of the superclass
public void display() {
System.out.println("display() in Derived.");
}
}
class Overridden {
public static void main(String args[]) {
Derived obj = new Derived();

// invoking the display() method of the Derived class


obj.display();
}
}
Exception Handling Statements
general form of these statements:
try {
statement(s)
} catch (exception type name) {
statement(s)
} finally {
statement(s)
}
Exception Handling (in outline)
• Format of code:

statements; a try block


try {
a catch block
code...;
}
catch (Exception-type et) {
code for dealing with et exception
}
more-statements;
Basic Approach
• The programmer wraps the error-prone code
inside a try block.
• If an exception (error) occurs anywhere in the
code inside the try block, the catch block is
executed immediately
– the block can use information stored in the et object
• After the catch block (the catch handler) has
finished, execution continues after the catch
block (in more-statements).
– execution does not return to the try block

continued
Exception Handling (in more detail)
• There can be many catch blocks associated with a try
block .
statements;
try {
code...;
}
catch (NullPointerException e) {
code for dealing with a NULL pointer
exception
}
catch (IOException e) {
code for dealing with an IO exception
}
catch (MyOwnException e) {
code for dealing with a user-defined
exception
}
more-statements;
What can a catch handler do?
• A handler can contain any Java code.
• Typical handler actions are to:
– print a message, and exit the program; or
– reset variables, and recall the method; or
– issue (throw) its own exception
What if there is no exception?
• If the try block finishes successfully without
causing an exception, then execution skips to
the code after the catch block.
Types of Exceptions
• Common exceptions:
– division by zero
– accessing an array outside its bounds

• Exceptions are organised into classes, with


Exception being the most general.
User-defined Exceptions
• The programmer can define new classes of
exceptions by extending the Exception
classes.

• Most commonly, the RuntimeException


classes are extended to deal with new kinds
of run-time errors.
The finally Block
• If a finally block is present it must be placed after the last
catch handler.
try {
code...;
}
catch (Exception-type et) {
code for dealing with et exception
}
finally {
code...;
}

• A finally block is always executed, even if:


– an exception is thrown inside the try block, or
– code does an ordinary return
• It is executed after the catch handler.
• Typical usage is to free system resources before terminating
– e.g. close files, network links
class ExTest {
public static void main(String args[]) {
int i = 0;

String greetings [] = { "Hello world!",


"No, I mean it!",
"HELLO WORLD!!" };

while (i < 4) {

// exception will be occured when refering to greetings[3]


System.out.println(greetings[i]);
i++;
}
}
}
class ExTest2 {
public static void main(String args[]) {
int i = 0;
String greetings [] = { "Hello world!", “Hi", “Welcome” };
while (i < 4) {
try {
System.out.println(greetings[i]);
} catch (ArrayIndexOutOfBoundsException e) {

// if an out-of-bounds access occures,


// shows message and the program will be continued
System.out.println("*** caught exception ");
} finally {
// executing finally block at any times
System.out.println("This is always printed.");
}
i++;
}
}
}
Packages
• A Java package is a collection of classes
• The package statement is used to specify that all
classes defined in a file belong to a particular
package.
• The syntax of the package statement is:
package package-name;
It must be located at the top of a file, and there can
be only one package statement per file.

103
Interfaces
• A Java interface is a collection of constants and abstract
methods.
• A class that implements an interface must provide
implementations for all of the methods defined in the
interface
• This relationship is specified in the header of the class:
class class-name implements interface-name {
}

104
Interfaces
• An interface can be derived from another
interface, using the extends reserved word
• The child interface inherits the constants
and abstract methods of the parent
• A class that implements the child interface
must define all methods in both the parent
and child

105
What is JDBC?
• JDBC is an interface which allows Java code to
execute SQL statements inside relational databases
– the databases must follow the ANSI SQL-2 standard
 What do we mean by JDBC Driver ?
Java Database Connectivity (JDBC) technology
is how the Java language works with databases,
the Java Database Connectivity (JDBC) API,
allows Java programs to access relational
databases and interact with them.
JDBC in Use

Java JDBC
program driver
connectivity for Oracle
data processing
utilities driver
for DB2

jdbc-odbc odbc
bridge driver
Four Kinds of JDBC Driver
• 1. JDBC-ODBC Bridge
– translate Java to the ODBC API

• 2. Native API
– translate Java to the database’s own API
• 3. Native Protocol
– use Java to access the database more directly using its low level
protocols

• 4. Net Protocol
– use Java to access the database via networking middleware
(usually TCP/IP)
– required for networked applications
The JDBC-ODBC Bridge
• ODBC (Open Database Connectivity) is a
Microsoft standard from the mid 1990’s.
• It is an API that allows programs to execute SQL
inside databases
• ODBC is supported by many products.
• The JDBC-ODBC bridge comes free with the
JDK:
– called sun.jdbc.odbc.JdbcOdbcDriver
• The ODBC driver for Microsoft Access comes
with MS Office
– so it is easy to connect Java and Access
Continued
JDBC Access Steps
All JDBC programs do the following:

1) load (Register ) the JDBC driver


Class.forName("oracle.jdbc.driver.OracleDriver");
2) Specify the name and location of the database being used.
String url="jdbc:oracle:thin:scott/tiger@193.188.73.12:1521:A8”;
3) Connect to the database with a Connection object
Connection conn=DriverManager.getConnection(url);
4) Execute a SQL query using a Statement object
String sql="select empno,ename from emp";
Statement stmt=conn.createStatement();

5) Get the results in a ResultSet object


Resultset rs=stmt.executeQuery(sql);

6) Finish by closing the ResultSet, Statement and Connection objects


conn.close();
DriveManager
• It is responsible for establishing the connection to
the database through the driver.
• e.g.
Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn =
DriveManager.getConnection(url);
Name the Database
• The name and location of the database is given as a URL
– the details of the URL vary depending on the type of database that is
being used
ODBC Database URL

jdbc:odbc: //host.domain.com: 2048 /data/file

The comms The machine The port The path to


protocol holding the used for the the database
database. connection. on the machine

e.g. jdbc:odbc:Books
jdbc:oracle:thin:scott/tiger@193.188.73.12:1521:A8
Statement Object
• The Statement object provides a
‘workspace’ where SQL queries can be
created, executed, and results collected.
• e.g.
Statement st =
conn.createStatement():
ResultSet rs = st.executeQuery(
“ select * from Authors” );
:
st.close();
ResultSet Object
• Stores the results of a SQL query.

• A ResultSet object is similar to a ‘table’


of answers, which can be examined by
moving a ‘pointer’ (cursor).

Continued
cursor
23 Daher
5 Sirin
17 Emad
98 Odeh
• Cursor operations:
– first(), last(), next(), previous(), etc.

• Typical code:
while( rs.next() ) {
// process the row;
}
simpJDBC.java
// simpJDBC.java
// Displays the firstnames and lastnames
// of the Authors table in the Books db.

import java.sql.*;

public class simpJDBC {

public static void main(String[] args)


{
// The URL for the Books database.
// ’Protected' by a login and password.
String url = "jdbc:odbc:Books";
String username = "anonymous";
String password = "guest";
:
try {
// load the JDBC-ODBC Bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// connect to db using DriverManager


Connection conn =
DriverManager.getConnection( url,
username, password );

// Create a statement object


Statement statement = conn.createStatement();

// Execute the SQL query


ResultSet rs = statement.executeQuery(
"SELECT lastName, firstName FROM Authors" );
:
// Print the result set
while( rs.next() )
System.out.println(
rs.getString("lastName") + ", " +
rs.getString("firstName") );

// Close down
statement.close();
conn.close();
}
:
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}

catch ( SQLException sqlex ) {


System.err.println( sqlex );
sqlex.printStackTrace();
}

} // end of main()

} // end of simpJDBC class


Username & Password
• The database’s link to the outside (e.g. its
ODBC interface) must be configured to
have a login and password
7. Books.mdb as an ODBC Data Source

• 1. Click on
“32 bit ODBC”
in the Control
Panel.
This displays the
ODBC Data
Sources
Administrator
• 2. Press “Add’ to
add a data source
and select
Microsoft Access
Driver (*.mdb).
Press “Finish”.
• 3. Type in a
data source
name,
description, and
press “Select”
to browse to set
the path to the
Books.mdb file.

Now click on
“Advanced”.
• 4. Type in a username
and password (guest).
Click “Ok”
Accessing a ResultSet
• The ResultSet class contains many methods for
accessing the value of a column of the current row
– can use the column name or position
– e.g. get the value in the lastName column:
rs.getString("lastName")
• The values are SQL data, and so must be
converted to Java types/objects.

• There are many methods for accessing/converting


the data, e.g.
– getString(), getDate(), getInt(),
getFloat(), getObject()
SQL Statements
• They can be defined into two types:
– those using the Data Definition Language
(DDL)
• create, delete tables
– those using the Data Manipulation Language
(DML)
• select
• others, including insert, update, delete
Executing DDL and DML
statements are executed from JDBC
• select
with executeQuery().
• The method returns a table of results
(a resultSet object).
• e.g.
ResultSet rs =
statement.executeQuery(
"SELECT lastName, firstName
FROM Authors" );

continued
executeUpdate()
• But most SQL statements do not return a table
– DDL statements, e.g. create, drop
– most DML statements, e.g. insert, update

• If you try to execute these kinds of statements


with executeQuery(), an SQLException will occur.
• executeUpdate Used to execute SQL statements
that change the database, table, or row
– e.g. DDL: create, drop
– e.g. DML: insert, update, delete
BuildTables.java
• This program uses create and insert to build
a new table, called urlInfo, inside
Books.mdb.
Code
// BuildTables.java
// Create a new table, urlInfo, inside Books.mdb
// The table has three columns: id, name, url

import java.sql.*;

public class simpJDBC {

public static void main(String[] args)


{
// The URL for the Books database.
// ’Protected' by a login and password.
String url = "jdbc:odbc:Books";
String username = "anonymous";
String password = "guest";
:
// SQL table creation and insertion
String[] SQLStats = {
"create table urlInfo (id int,Name char(48),
url char(80))",
"insert into urlInfo values(1, ‘Daher Thabit',
'http://www.rss.gov.jo/~daher')",
"insert into urlInfo values(2,
‘National Information Centre',
'http://www.nic.gov.jo')",
"insert into urlInfo values(3, ‘Sun',
'http://www.sun.com')” };
try {
// load the JDBC-ODBC Bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// connect to db using DriverManager
Connection conn =
DriverManager.getConnection( url,
username, password );
:
// Create a statement object
Statement statement =
conn.createStatement();

// Create urlInfo table


for (int i = 0; i < SQLStats.length; i++) {
statement.executeUpdate(SQLStats[i]);
System.out.println("Processed: " +
SQLStats[i]);
}

// Close down
statement.close();
conn.close();
}
:
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}

catch ( SQLException sqlex ) {


System.err.println( sqlex );
sqlex.printStackTrace();
}

} // end of main()

} // end of BuildTables class


• Current Information:
http://www.javasoft.com/products/jdbc

• A searchable list of drivers (freeware,


shareware, and commercial) can be found
at:
http://www.javasoft.com/products/
jdbc/drivers
Threading

Threads

• Objectives
– describe basic threads in Java
Contents
1. What is Concurrency?
2. Java Threads
3. Scheduling
1. What is Concurrency?
• Concurrency (parallelism) allows several
tasks/jobs to be done at the same time.
• For example:
– a person can walk, talk and breath at the same time
– a computer can compile a program, print a file, and
receive e-mail at the same time
• Most programming languages do not have
concurrent features
– e.g. a program that cannot do several tasks at once

continued
• C does not have concurrency features, but it can use
concurrency functions from UNIX
– leads to code that is low level, and hard to understand

• The first mainstream language to have concurrent


language features was Ada (~1980).

• Java’s concurrent language features (called threads).


2. Java Threads
• A program can have many threads of
execution
– each thread runs concurrently and does one
task
– e.g. a program can have several threads
download large audio files from the Web, and
another thread play the files as they arrive
2.1. Two Ways to Make a Thread

• 1. Extend class Thread and override run():


class Mango extends Thread {
public void run()
{ /* do task */ }
}

// Thread creation
Mango m = new Mango();
m.start();

continued
• 2. Implement the Runnable interface and
override run():
class Pineapple implements Runnable {
public void run()
{ /* do task */ }
}

// Thread creation
Thread pat1 = new Thread( new Pineapple() );
pat1.start();
2.2. start() and run()
• Threads do not automatically start executing
when created (with new)
– they must be started with start()

• start() will automatically call run()

• Programmers override run(); they do not


alter start()
2.3. threadExs.java
• // The two ways to obtain a thread of code
// 1. extend class Thread
// 2. implement the Runnable interface

import java.io.*;

class threadExs {
public static void main(String[] a)
{
SimpThread t1 = new SimpThread();
t1.start();

Thread t2 = new Thread (new SimpRunnable());


t2.start();
}
}

continued
class SimpThread extends Thread {
// 1. extend class java.lang.Thread
public void run()
{ for(int i = 0; i < 300; i++)
System.out.println(i +
". Extension of THREAD running");
}
}

class SimpRunnable implements Runnable {


// 2. implement the Runnable interface,
public void run()
{ for (int i = 0; i < 300; i++)
System.out.println(i +
". Implem. of RUNNABLE running");
}
}
Usage
• $ java threadExs
0. Extension of THREAD running
1. Extension of THREAD running
2. Extension of THREAD running t1 starts
:
17. Extension of THREAD running
0. Implem. of RUNNABLE running
18. Extension of THREAD running t1 and t2
1. Implem. of RUNNABLE running
: alternate
299. Extension of THREAD running
282. Implem. of RUNNABLE running
299. Implem. of RUNNABLE running t1 ends
:
282. Implem. of RUNNABLE running and t2
$ continues
2.4. Runnable vs. Thread
• The Thread class contains a range of useful
methods:
– run(), sleep(), getName(), etc.

• The Runnable interface only has run()


– but once a Runnable object is running as a
thread, a Thread object for it can be accessed
– then the Thread methods can be used
2.5. threadExs2.java
A thread and a Runnable
• import java.io.*; object that both sleep

class threadExs2 {
public static void main(String[] a)
{
SleepThread t1 = new SleepThread();
t1.start();

Thread t2 = new Thread (new SleepRunnable());


t2.start();
}
}
class SleepThread extends Thread {
public void run()
{
for(int i = 0; i < 300; i++) {
System.out.println(i +
". Extension of THREAD running");
if (i == 50) {
System.out.println(
"**** SleepThread going to sleep");
try{ sleep(5000); }
catch (InterruptedException ie) { return; }
System.out.println(
"**** SleepThread waking up");
}
}
}
}
class SleepRunnable implements Runnable {
public void run()
{
for (int i = 0; i < 300; i++) {
System.out.println(i +
". Implem. of RUNNABLE running");
if (i == 250) {
System.out.println(
"**** SleepRunnable going to sleep");
Thread rt = Thread.currentThread();
try{ rt.sleep(7000); }
catch (InterruptedException ie) {return; }
System.out.println(
"**** SleepRunnable waking up");
}
}
}
}
Usage
• 0. Extension of THREAD running
1. Extension of THREAD running
2. Extension of THREAD running t1 starts
:
17. Extension of THREAD running
0. Implem. of RUNNABLE running
18. Extension of THREAD running
1. Implem. of RUNNABLE running t1 and t2
:
50. Extension of THREAD running alternate
33. Implem. of RUNNABLE running
**** SleepThread going to sleep
34. Implem. of RUNNABLE running t1 goes to sleep
35. Implem. of RUNNABLE running
:
t2 runs
alone
250. Implem. of RUNNABLE running t2 goes to sleep
**** SleepRunnable going to sleep
**** SleepThread waking up later, t1 wakes up
51. Extension of THREAD running
52. Extension of THREAD running t1 runs alone
:
to its finish
299. Extension of THREAD running
**** SleepRunnable waking up
later, t2 wakes up
251. Implem. of RUNNABLE running
252. Implem. of RUNNABLE running
: t2 runs to
299. Implem. of RUNNABLE running to its finish
$
2.6. Why use Runnable?
• The big advantage of Runnable is that it is an
interface: a class can implement many
interfaces, but can only extend one class.
– e.g.
class FooBar extends JApplet
implements Runnable,
ActionListener
but not: ERROR
class FooBar extends JApplet, Thread
implements ActionListener
3. Scheduling
• The JVM scheduler decides how much time to give
to each thread for running.

• Most schedulers use time slicing.


– 1) Each thread gets a small amount of time to run (called
a time slice).
– 2) When the time is used up, the thread is automatically
suspended (if it has not finished).
• i.e. the execution of run() is suspended

continued
3) The suspended thread waits until all the other
threads have had a turn, before it is automatically
woken up
• i.e. the execution of run() starts from where it was
suspended

• The idea of giving each thread a turn is called


round-robin scheduling.

• There are many other scheduling algorithms


– e.g. threads can have different priorities
• a high priority thread can get a turn more quickly
3.1. Scheduling Problem in Java
• Java on different OSes do not use the same
scheduling mechanism
– Java on Windows uses time slices and round-
robin scheduling good
• every threads gets a turn

– Java on Solaris does not use time slices bad


• a thread executes until it finishes; others must wait

continued
• How can threads be made to give turns?
– the yield() function can be called in a thread to force
it to time slice

– yield() is also sometimes useful in Windows-based


code to make the time slicing happen more often

• In the future, all the JVMs will use time slicing


3.2. drinks.java
Using yield() to improve
public class drinks fairness in Window
{
public static void main(String[] a)
{
Coffee cof1 = new Coffee(300);
cof1.start();

// an anonymous thread
new Coffee(270).start();

new Tea(250).start(); // another anon. thread


}
}

continued
class Coffee extends Thread
{ private int numCups;

public Coffee(int n)
{ numCups = n; }

public void run()


{
while(numCups > 0) {
System.out.println(numCups + ". " +
getName() + " likes coffee");
numCups--;
yield(); // must appear for solaris;
// optional in Win9x
}
}
}

continued
class Tea extends Thread
{ private int numCups;

public Tea(int n)
{ numCups = n; }

public void run()


{
while(numCups > 0) {
System.out.println(numCups +
". I like tea");
numCups--;
yield(); // must appear for solaris;
// optional in Win9x
}
}
}
with the yield() calls commented out
Usage
• $ java drinks
250. I like tea tea thread begins
:
242. I like tea
300. Thread-0 likes coffee first coffee
299. Thread-0 likes coffee
: thread begins
259. Thread-0 likes coffee
258. Thread-0 likes coffee
241. I like tea
270. Thread-1 likes coffee
257. Thread-0 likes coffee second coffee
240. I like tea
269. Thread-1 likes coffee thread begins
256. Thread-0 likes coffee
:

continued
2. I like tea
31. Thread-1 likes coffee
18. Thread-0 likes coffee
1. I like tea tea thread finishes
:
30. Thread-1 likes coffee
17. Thread-0 likes coffee
29. Thread-1 likes coffee
16. Thread-0 likes coffee
:
15. Thread-1 likes coffee
2. Thread-0 likes coffee
14. Thread-1 likes coffee
1. Thread-0 likes coffee
13. Thread-1 likes coffee first coffee
12. Thread-1 likes coffee
: thread finishes
2. Thread-1 likes coffee
1. Thread-1 likes coffee
$
second coffee
thread finishes
Usage with the yield() calls in

• $ java drinks
300. Thread-0 likes coffee The three threads
270. Thread-1 likes coffee start together
250. I like tea
299. Thread-0 likes coffee
269. Thread-1 likes coffee
249. I like tea
:
22. Thread-1 likes coffee
52. Thread-0 likes coffee
2. I like tea
21. Thread-1 likes coffee
51. Thread-0 likes coffee
1. I like tea
: tea thread finishes

continued
20. Thread-1 likes coffee
50. Thread-0 likes coffee
19. Thread-1 likes coffee
49. Thread-0 likes coffee
:
2. Thread-1 likes coffee
32. Thread-0 likes coffee
1. Thread-1 likes coffee
31. Thread-0 likes coffee second coffee
30. Thread-0 likes coffee thread finishes
:
2. Thread-0 likes coffee
1. Thread-0 likes coffee
$ first coffee
thread finishes
Graphics

• Objective
– look at color, fonts, and how to draw
shapes into applet/application windows
Graphics

• Objective
– look at color, fonts, and how to draw
shapes into applet/application windows
Java’s Coordinate System
• Graphical methods use an (X,Y) coordinate
system to place things in a window:
0 +x
0 X axis

(X,Y)
note
+y
Y axis
Coordinate
Graphics Objects and Contexts
• Drawing graphics into an applet/application
window is a two-stage process:
– 1) the graphics object for the window must be
obtained
– 2) drawing is done into the window by calling
methods in the graphics object

window graphics
object call methods

continued
• A graphics object contains methods and
data related to drawing:
– e.g. the drawing area, current font, color
– often called a graphics context

• Graphics objects are instances of the


Graphics class.

continued
• Good news: The programmer does not have
to directly obtain the graphics object for the
applet/application window
– the runtime system supplies it as an argument to
paint()
– the programmer must redefine paint() to
modify/use its graphics object argument
Graphics Methods: paint()
• public void paint(Graphics g);
– draws the graphics context stored in g which
represents the applet/application window

– called by the runtime system at certain times


– the programmer does not call paint() directly

continued
– paint() is called automatically at the start to
draw the window, and whenever the window
needs to be redisplayed
• e.g when the window was hidden and is uncovered
repaint()
• public void repaint()
– its default behaviour is to call update() and then
paint()
– programmers often call this method directly in order to
request a repaint of the window

– a variation of repaint() specifies a subregion of the


window to repaint
• repaint(x,y,width,height)
• the rest of the window is unchanged
show()
• Sometimes used in applications to make
the window visible.
Drawing Methods
• The names of the methods for drawing text,
lines, shapes, etc. are very similar:
– public void drawXXX(...);
– public void fillXXX(...);

– “XXX” is replaced by String, Line, Rect,


RoundRect, 3DRect, Arc, Polygon, ...

continued
• drawXXX() puts an empty outline on the
screen.
• fillXXX() fills the interior with a solid
colour.

• The drawing colour is the ‘foreground’


colour
– set with setColor(Color c)
What is an Applet ?
• An Applet is a Java class that you can embed
in an HTML page, and is downloaded and
executed by a Web browser.
Applet Class Hierarchy
java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Window java.awt.Panel

java.awt.Frame java.applet.Applet
Java Applets

Java source Java Java


code compiler bytecode

Web browser

Java
interpreter
MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
public void paint(Graphics g)
{
……………….;
………………..;
}
}
Simple HTML document
<HTML>
<HEAD>
<TITLE>My First Applet</TITLE>
</HEAD>
<BODY>
<APPLET code=”MyApplet.class”
width=500
height=300>
</APPLET>
</BODY>
</HTML>
Drawing String Example
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
public void paint(Graphics g)
{
g.drawString(“Hello Daher”,25,25); // x and y
}
}
What is the appletviewer ?
A Java application that:
• Enables you to run applets without using a
Web browser.
• Loads the HTML file supplied as an
argument
Applet Life Cycle

• public void init();


• public void start();
• public void stop();
• public void destroy();
Colors
• A colour is defined using an RGB
(Red/Green/Blue) triplet of values:
– 3 integers, each in the range 0 to 255
(or 3 floats, each in the range 0.0 to 1.0)

– as a number gets bigger, so the amount of color


increases
0 = black (off)
1 = full on
Colors
• Color is not a property of a particular
rectangle,string or other thing you may draw.
• Rather color is a part of the Graphics object
that does the drawing.
• To change colors you change the color of
your Graphics object. Then everything
you draw from that point forward will be in
the new color, at least until you change it
again.
Predefined Colors
• Color RGB triple
public final static Color orange 255,200,0
public final static Color pink 255,175,175
public final static Color black 0,0,0
public final static Color white 255,255,255
public final static Color red 255,0,0
public final static Color green 0,255,0
public final static Color blue 0,0,255
:
Common Colors

•Color.black •Color.lightGray
•Color.blue •Color.magenta
•Color.orange
•Color.cyan
•Color.pink
•Color.darkGray •Color.red
•Color.gray •Color.white
•Color.green •Color.yellow
Color Methods
• public Color(int r, int g, int b);
public Color(float r, float g, float b);
– creates a Color object based on the RGB values
– e.g. Color c = new Color(0,0,0);

• public abstract void setColor(Color c);


– sets the foreground colour of the graphics
object
– e.g. g.setColor(c);
continued
• public abstract Color getColor();
– returns a Color object set to the foreground
colour of the graphics object
– e.g. c = g.getColor();

• public int getRed();


public int getBlue();
public int getGreen();
– returns the colour value as an int
– e.g. c.getRed();
Fonts
• A Font object is defined using three
attributes:
– its name (e.g. “TimesRoman”)
– its style (e.g. ITALIC)
– its point size (e.g. 24)

continued
• Creating a Font object:
public Font(String name, int style, int size);
e.g.
Font f = new Font(“TimesRoman”,
Font.BOLD, 18);

• Set the graphic object’s font:


public abstract void setFont(Font f);
e.g. g.setFont(f);

continued
Serif Monospaced
SansSerif
• Five font names can be assumed:
– TimesRoman, Courier, Helvetica, Symbol,
Dialog

• Some style constants in the Font class:


– public final static int PLAIN
public final static int BOLD
public final static int ITALIC
Lines, Rectangles, Ovals
1. Lines
• public void drawline( int x1, int y1,
int x2, int y2);

– draw a line between (x1,y1) and (x2,y2) in the


current colour

(x1,y1)

(x2,y2)
Drawing Lines
import java.applet.*;
import java.awt.*;
public class SimpleLine extends Applet {
public void paint(Graphics g) {
g.drawLine(5,10,20,30);
}
}
(x,y) width

2. Rectangles height

• public void drawRect(int x, int y,


int width, int height);
– draw a rectangle of the specified width and
height. Its top-left corner is at (x,y).

• public void fillRect(int x, int y,


int width, int height);
– draw a solid rectangle. Use the current
foreground colour.
continued
rectangle
window

• public void clearRect(int x, int y,


int width, int height);

– Use the current background colour (i.e. the colour of


the window).
– Frequently used to ‘erase’ something by covering it
with the background colour
Drawing Rectangles
import java.applet.*;
import java.awt.*;
public class RectangleApplet extends Applet {
public void paint(Graphics g) {
g.drawRect(35,15, 125,200);
}
}
3. Rounded Rectangles

• A rectangle with rounded corners:

(x, y) arc height

arc width height

width continued
• public void drawRoundRect(
int x, int y,
int width, int height,
int arcWidth, int arcHeight);

• public void fillRoundRect(


int x, int y,
int width, int height,
int arcWidth, int arcHeight);
4. 3D Rectangles
• These are ordinary rectangles with shading
along two edges, to make them look three
dimensional.
• Two types: raised and lowered

continued
• public void draw3DRect(
int x, int y,
int width, int height,
Boolean raised);
– The rectangle is raised if raised is true;
otherwise lowered.

• public void fill3DRect(


int x, int y,
int width, int height,
Boolean raised);
5. Ovals and Circles
• Dimensions of an oval:

(x, y)

height

width

continued
• public void drawOval(
int x, int y,
int width, int height);

• public void fillOval(


int x, int y,
int width, int height);
6. Arcs
• An arc is a portion of an oval.
• An arc is drawn between two angles:
– a starting angle and and an arc (ending) angle

(x,y) 90

0 degrees
height 180
ending starting angle
angle
width 270
continued
positive sweep

negative sweep

• A positive sweep measures the angle in the


“counter-clockwise” direction
– the angle is a positive value (e.g. 275)
• A negative sweep measures the angle in the
“clockwise’ direction
– the angle is a negative value (e.g. -85)

continued
a positive number means “positive
sweep”; negative means “negative
sweep”

• public void drawArc(


int x, int y,
int width, int height,
int startAngle, int arcAngle);

• public void fillArc(


int x, int y,
int width, int height,
int startAngle, int arcAngle);
Examples
7. Polygons and Polylines
• Polygons are multi-sided shapes,
represented by a series of (x,y) points.

• Polylines are a series of points connected by


straight lines.

continued
• Polygons are closed shapes.
• Polylines may be open or closed
– an open polyline does not end where it began
e.g. the example on the previous slide

• Only polygons can be filled with colour


– since they are closed
Polygon Methods
• public Polygon(int xs[], int ys[],
int num);
– returns a new Polygon object with num
sides; x coordinates from xs[],
y coordinates from ys[]
– e.g.
int xs = {20,30,20};
int ys = {20,30,40};
Polygon p = new Polygon(xs,ys,3);

continued
(20,20)
(30,30)

(20,40)
• public void drawPolygon(Polygon p);
– draw the polygon p in the graphics object
– e.g. g.drawPolygon(p);

• public void fillPolygon(Polygon p);


– draw the filled polygon; use the current colour
– e.g. g.fillPolygon(p);
Polyline Method
• public abstract void drawPolyLine(
int xs[], int ys[], int num);

– draw the polyline specified by the coordinates


in xs[] and ys[]; num is the number of points

– if the last point is different from the first then


the polyline is open

continued
(20,20)
(30,30)

(20,40)
• e.g.
int xs = {20,30,20};
int ys = {20,30,40};
g.drawPolyline(xs,ys,3);
Examples
8. Java 2D
• Java 2D was introduced in JDK 1.2. to deal
with graphics weaknesses
– e.g. single-pixel thickness lines, limited fonts,
poor shape manipulation (e.g. no rotation), no
special fills/gradients/patterns inside shapes,
poor image support
8.1. Using Java 2D
• Redefine paint() as before, but the graphics
context must be cast to type Graphics2D
before the Java 2D operations can be used.

• public void paint(Graphics g)


{
Graphics2D g2 = (Graphics2D)g;
: // call Java 2D methods on g2
}
8.2. Examples

continued
8.3. More Information
• Java 2D Graphics / Jonathan Knudsen
O’Reilley, 1999
Beyond Java 2D
• Java 3D
– create 3D objects (e.g. boxes, spheres)
– build virtual worlds, controlled by Java!
– http://java.sun.com/products/
java-media/3D/
• Java Advanced Imaging API (JAI)
– very sophisticated image processing
– http://java.sun.com/products/
java-media/jai/
AWT Controls Overview
We list the AWT controls in two
categories:
– basic controls
– top-level containers
Basic Controls
• Control AWT Class Name
– button Button, CheckBox
– choice Choice
– list List
– menu Menu, MenuBar, MenuItem
– text field TextField
– label Label
– text TextArea
Top-level Containers
• Container AWT Class Name
– frame Frame
Examples
import java.awt.*
import java.applet.*;
public class ButtApplet extends Applet {
Button button1, button2, button3, button4;
Public void init(){
button1=new Button(“button1”);
button2=new Button(“button2”);
button3=new Button(“button3”);
button4=new Button(“button4”);
add(button1);
add(button2);
add(button3);
add(button4);
}}
Swing GUI components
• In JDK 1.2 and later, GUI interfaces should
be written with the Swing GUI components

• Swing includes buttons, text fields, scrolling


windows, editor windows, tree displays, etc
– we will describe some of them
1.1. Swing and AWT
• In older Java programs, the AWT (Abstract
Window Toolkit) GUI components are used
– Swing has replaced AWT GUIs
– never mix Swing and AWT GUIs in a single
program

• Some parts of AWT are still used


– e.g. the layout managers

continued
• Swing supports lightweight GUI components
– they are drawn onto the screen in an area
controlled by Java
– the GUI is implemented completely within the
JVM
– advantage: the 'look' of GUI components can be
controlled by Java

continued
• AWT supports heavyweight GUI components
– each Java GUI component is actually a simple
layer hiding the OSes GUI component
• the OS component is called a peer component

– e.g. on Windows, a Java button in AWT is


implemented using a Windows' button

continued
1.2. Disadvantages of AWT
• Java does not have complete control over
the AWT GUI components
– some JAVA AWT GUIs do not work because of
problems with the underlying OS (e.g. file
choosing in Windows)

• The "look and feel" of Java GUIs in AWT


vary between OSes.
2. Three Steps to GUIs
• There are three main steps to creating a GUI
for a Java program:
– 1. Declare the GUI controls;

– 2. Implement the event handlers for the


controls;

– 3. Position the controls on the screen by using


layout managers and/or containers.
2.1. Some Definitions

• Control
– a control is a GUI element
• e.g. a button, textfield, scrollbar

continued
• Container
– a container is way of grouping controls (or
other containers)
– this makes it simpler to move, hide, or show a
group of controls, since the container can be
manipulated
– 'top-level' containers in Java include JFrame
and JApplet

continued
• Component
– Java uses the word 'component' to talk about
controls and containers
– the Swing package supports GUI components,
such as buttons, text fields (controls), and
frames and applets (containers)

– The Swing implementation has every control


and container inherit from JComponent
Basic Graphics Examples
• // Graf1.java
import javax.swing.*;
import java.awt.*;

public class Graf1 extends JApplet


{
public void paint(Graphics g)
{
// set the ‘foreground’ color
g.setColor(Color.red);
g.drawString("Hello", 25, 25);
}
}

continued
• Graf1.html:
<html>
<applet code="Graf1.class" width="200"
height="100">
</applet>
</html>
Use
• appletviewer Graf1.html
Graf2.java
• import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // for window listener

public class Graf2 extends JFrame {


public Graf2() {
super("Graf2");
setSize(200, 100); // includes title bar
show();
}

public void paint(Graphics g) {


g.setColor(Color.red);
g.drawString("Hello", 25, 50); // below title }
:
public static void main(String args[])
{
Graf2 gf2 = new Graf2();

gf2.addWindowListener(
// anonymous class for window closing
new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); }
}
);
} // end of main()

} // end of Graf2 class


Use
• java Graf2
ShowColors.java
• import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class ShowColors extends JFrame {


public ShowColors()
{
super( "Using colors" );
setSize( 400, 130 );
show();
}
:
public void paint( Graphics g )
{
// set new drawing color using integers
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " +
g.getColor(), 130, 40 );

// set new drawing color using floats


g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " +
g.getColor(), 130, 65 );
:
// set new drawing color
g.setColor( Color.blue );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " +
g.getColor(), 130, 90 );

// display individual RGB values


Color c = Color.magenta;
g.setColor( c );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + c.getRed() +
", " + c.getGreen() +
", " + c.getBlue(), 130, 115 );

} // end of paint()
:
public static void main( String args[] )
{
ShowColors app = new ShowColors();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit( 0 ); }
}
);
} // end of main()

} // end of ShowColors
Use
Fonts.java
• import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Fonts extends JFrame {


public Fonts()
{
super( "Using fonts" );
setSize( 420, 125 );
show();
}
:
public void paint( Graphics g )
{
// set current font to Serif (Times), bold,
// 12pt and draw a string
g.setFont( new Font("Serif",Font.BOLD, 12));
g.drawString("Serif 12 point bold.",20,50);

// set current font to Monospaced (Courier),


// italic, 24pt and draw a string
g.setFont(
new Font("Monospaced",Font.ITALIC,24));
g.drawString( "Monospaced 24 point italic.",
20, 70 );
:
// set font to SansSerif (Helvetica),
// plain, 14pt and draw a string
g.setFont(
new Font("SansSerif", Font.PLAIN, 14) );
g.drawString("SansSerif 14 pt plain.",20,90 );

// set font to Serif (times), bold/italic,


// 18pt and draw a string
g.setColor( Color.red );
g.setFont(
new Font( "Serif",
Font.BOLD + Font.ITALIC, 18 ) );
g.drawString( g.getFont().getName() + " " +
g.getFont().getSize() +
" point bold italic.", 20,110);

} // end of paint()
:
public static void main( String args[] )
{
Fonts app = new Fonts();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit( 0 ); }
}
);
} // end of main()

} // end of Fonts
Use
LinesRectsOvals.java
• // Drawing lines, rectangles and ovals
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LinesRectsOvals extends JFrame


{
public LinesRectsOvals()
{
super( "Drawing lines, rectangles
and ovals" );
setSize( 400, 165 );
show();
}
:
public void paint( Graphics g )
{ g.setColor( Color.red );
g.drawLine( 5, 30, 350, 30 );

g.setColor( Color.blue );
g.drawRect( 5, 40, 90, 55 );
g.fillRect( 100, 40, 90, 55 );

g.setColor( Color.cyan );
g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
g.drawRoundRect( 290, 40, 90, 55, 20, 20 );

g.setColor( Color.yellow );
g.draw3DRect( 5, 100, 90, 55, true );
g.fill3DRect( 100, 100, 90, 55, false );

g.setColor( Color.magenta );
g.drawOval( 195, 100, 90, 55 );
g.fillOval( 290, 100, 90, 55 );
} // end of paint()
:
public static void main( String args[] )
{
LinesRectsOvals app =
new LinesRectsOvals();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit( 0 ); }
}
);
} // end of main()
} // end of LinesRectsOvals class
Use
Swing Controls Overview
• We list the Swing controls in six categories:
– basic controls
– uneditable displays
– editable displays
– space-saving containers
– top-level containers
– other containers
Basic Controls
• Control Swing Class Name
– button JButton, JCheckBox, JRadioButton
– combo box JComboBox
– list JList
– menu JMenu, JMenuBar, JMenuItem
– slider JSlider
– toolbar JToolbar
– text field JTextField, JPasswordField
Uneditable Displays
• Control Swing Class Name
– label JLabel
– Tooltip JToolTip
– Progress bar JProgressBar
Editable Displays
• Control Swing Class Name
– table JTable
– text JTextPane, JTextArea,
JEditorPane
– tree JColorChooser
– file chooser JFileChooser
Space-saving Containers
• Container Swing Class Name
– scroll pane JScrollPane, JScrollBar
– split pane JSplitPane
– tabbed pane JTabbedPane
Top-level Containers
• Container Swing Class Name
– frame JFrame
– applet JApplet
– dialog JDialog, JOptionPane
Other Containers
• Container Swing Class Name
– panel JPanel
– internal frame JInternalFrame
– layered pane JLayeredPane
– root pane JRootPane

indirectly used by top-level


containers to gain access to
the content pane and other
'layers' of the container
JColorChooser
• JColorChooser is a SWING GUI for
interactively selecting colours
– intended for applications where the user needs
to select colours
• Two GUI programs:
– LabelTest.java (an application)
– LabelTest2.java (an applet)

• They use the JLabel and JToolTip controls,


which are uneditable, and so do not require event
handlers
– event handlers will be explained in the next section

continued
• The layout manager is FlowLayout
– explained later

• The application uses the top-level container


JFrame. The applet uses the top-level
container JApplet
– the most common containers
4.1. LabelTest.java
• // The JLabel GUI in a Java application

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LabelTest extends JFrame


{
public LabelTest()
{
super( "Testing JLabel" );

Container c = getContentPane();
step 1
c.setLayout( new FlowLayout() );
:
step 2
// JLabel with a string argument step 3
JLabel label1 =
new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
c.add( label1 );
step 4
// JLabel with string, Icon and alignment
Icon bug = new ImageIcon( "bug1.gif" );
JLabel label2 =
new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT );
c.add( label2 );

setSize( 200, 100 );


show();
} // end of LabelTest() step 5
public static void main( String args[] )
{
LabelTest app = new LabelTest();

app.addWindowListener( new WindowAdapter() {


public void windowClosing( WindowEvent e )
{ System.exit( 0 ); }
} );

} // end of main()

} // end of LabelTest class


Use
Notes
• The GUI is initialized in the class' constructor
method: LabelTest().

• Initialization steps:
– 1. get the container for the frame
– 2. set the layout manager (FlowLayout)
– 3. declare the controls
– 4. add them to the container
– 5. set the size of the window, and show it

continued
• Tooltip text can be added to all GUI controls.
label1.setToolTipText( "This is label1" );

• Labels can be constructed in several ways:


– the second label includes an image and alignment
information

• ImageIcon() is the standard way to load small


images.

continued
• The frame (window) is created by calling its
constructor inside main()

• main() also adds an event handler to the frame


– it causes the program to exit when a 'window closing'
event is output from the frame
– very common way to close a frame and exit
– more later
4.2. LabelTest2.java The applet version

// The JLabel GUI in a Java applet

import javax.swing.*;
import java.awt.*;
// import java.awt.event.*; // not needed

public class LabelTest2 extends JApplet


{
public void init()
{ step 1
Container c = getContentPane();
c.setLayout( new FlowLayout() );
: step 2
// JLabel with a string argument
step 3
JLabel label1 =
new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
c.add( label1 );
step 4
// JLabel with string, Icon and alignment
Icon bug = new ImageIcon( "bug1.gif" );
JLabel label2 =
new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT );
c.add( label2 );

} // end of init()

} // end of LabelTest2 class


LabelTest2.html
• <html>
<body>
<applet code="LabelTest2.class"
width="200" height="100">
</applet>
</body>
</html>
Use
c:> appletviewer LabelTest2.html
Notes
• The class extends JApplet not JFrame.

• There is no main().

• There is no constructor method in the class,


the initialization is done inside init()
– the usual place for GUI creation in applets

continued
• The initialization is similar, but a bit different:
– 1. get the container for the applet
– 2. set the layout manager (FlowLayout)
– 3. declare the controls
– 4. add them to the container
– but do not set the size of the window, or show it

• The size is set in LabelTest2.html, and the applet is


displayed automatically.

continued
• There is no need for an event handler for
closing the applet and exiting
– that is done automatically

• Since the code has no event handlers, there


is no need to import java.awt.event.*
– but in general applets do use event handlers
(see later)
Event Handlers
• An event handler is a method that is called
automatically when an event occurs in a
GUI component.

• Examples of events include:


– typing return in a text field
– pressing a button
– clicking the mouse over a component

continued
• Event handlers (methods) for different events are
predefined by Java inside listener classes.

• A listener class is an interface


– it defines the interfaces of its event handler methods
(i.e. the names, types of arguments)
– the programmer must implement each method to
respond to the event that triggers it

continued
Event Handler as a Diagram
class that implements
Program on-screen GUI the listener class
event event handler
method

data
methods
Program Code A typical action is for the
event handler method to
update the data back in the
program.
Using Event Handlers
• The programmer must:
– 1. Implement the listener classes, by coding
their event handler methods
– 2. 'Register' the GUI components in their
program with the implemented listener classes

• The Java runtime system will automatically


pass events to the handlers for processing.
Components and Events
• There are 10 Listener classes that can handle
events from different GUI components
– ActionListener
– ItemListener
– MouseListener and MouseMotionListener
– WindowListener
– KeyListener
– TextListener
– ComponentListener Not considered here
– ContainerListener
– FocusListener
ActionListener
• It deals with events from:
– JButton, JMenu, JMenuItem, JRadioButton,
JCheckBox
• when a control is pressed
– JTextField
• when enter is typed

• The interface has one method:


public void actionPerformed(ActionEvent e)
ItemListener
• It deals with events from:
– JButton, JMenu, JMenuItem, JRadioButton,
JCheckBox
• when an item in the control is selected

• The interface has one method:


public void itemStateChanged(ItemEvent e)

Some GUI components


generate multiple events
MouseListener
• It deals with mouse clicks over GUI
components.

• Its interface has 5 methods:


– public void mouseClicked(MouseEvent e)
– public void mousePressed(MouseEvent e)
– public void mouseReleased(MouseEvent e)
– public void mouseEntered(MouseEvent e)
– public void mouseExited(MouseEvent e)

continued
MouseMotionListener
• For efficiency reasons, mouse movement
events are dealt with by a separate listener.

• Its interface has 2 methods:


– public void mouseDragged(MouseEvent e)
– public void mouseMoved(MouseEvent e)
WindowListener
• It deals with events from:
We used this
– JDialog, JFrame, JWindow method in
LabelTest.java
• Its interface has 7 methods:
– public void windowOpened(WindowEvent e)
– public void windowClosing(WindowEvent e)
– public void windowClosed(WindowEvent e)
– public void windowIconified(WindowEvent e)
– public void windowDeiconified(WindowEvent e)
– public void windowActivated(WindowEvent e)
– public void windowDeactivated(WindowEvent e)
//Example
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

// a class which has some methods for dealing with mouse click events
public class MyEvent extends Applet implements MouseListener {
int mouseX = 20, mouseY = 40;
// register a mouse events handler
addMouseListener(this);
}
public void paint(Graphics g) {
g.drawString("Clicked point: " + mouseX + " " + mouseY, mouseX,
mouseY);
}
// the mouse button pressed and the released in one motion
public void mouseClicked(MouseEvent evt) {
mouseX = evt.getX();
mouseY = evt.getY();
repaint();
}

// when the mouse cursor enters a component


public void mousePressed(MouseEvent evt) {}

// when the mouse cursor later released


public void mouseReleased(MouseEvent evt) {}

// when the mouse cursor enteres a component


public void mouseEntered(MouseEvent evt) {}

// when the mouse cursor leaves a component


public void mouseExited(MouseEvent evt) {}
}
Butt.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Butt extends Applet implements ActionListener{
Button redbut, greenbut, bluebut;
Color red = Color.red;
Color green = Color.green;
Color blue = Color.blue;
Color current = red;
public void init(){
redbut = new Button("red");
greenbut = new Button("green");
bluebut = new Button("blue");
add(redbut);
add(greenbut);
add(bluebut);
current = red;
redbut.addActionListener(this);
greenbut.addActionListener(this);
bluebut.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == redbut){
redbut.setEnabled(false);
greenbut.setEnabled(true);
bluebut.setEnabled(true);
current = red;
}
if (e.getSource() == greenbut){
redbut.setEnabled(true);
bluebut.setEnabled(true);
greenbut.setEnabled(false);
current = green;
}
if (e.getSource() == bluebut){
redbut.setEnabled(true);
greenbut.setEnabled(true);
bluebut.setEnabled(false);
current = blue;
}
repaint();
}

public void paint(Graphics g){


g.setColor(current);
g.fillRect(100, 50, 200, 100);
}
}
Reducing Handler Coding
• When we implement an interface (a listener
class), we must implement all of the
methods inside it.

• Even if we only want to use one method, we


still have to give empty implementations for
all the other methods
– a lot of boring work for some listener classes
Long Example
• public class MyClose
implements WindowListener
{
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e)
{ System.exit(0); }
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}
Use in LabelTest.java
public static void main( String args[] )
{
LabelTest app = new LabelTest();

app.addWindowListener( new MyClose() );

}
• addWindowListener() is the way that the
listener is registered with the frame:
app.addWindowListener(...);

• Any window events output by app (the


frame) will go to the listener object
– it will only respond to a 'window closing' event
Existing Long Classes
• Java supplies predefined classes which implement
the bigger listener classes
– called adapter classes

• These adapter classes contain empty methods for


all the event handlers
– the programmer must inherit the adapter class, and
override the method they want with their own
definition
Existing Adapter Classes
• WindowAdapter
• MouseAdapter and MouseMotionAdapter
• FocusAdapter
• ContainerAdapter
• ComponentAdapter
• KeyAdapter
WindowAdapter.java
• public abstract class WindowAdapter
implements WindowListener
{
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e)
{}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e)
{}
}
Using WindowAdapter
• public class MyClose2
extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{ System.exit(0); }
}
Use in LabelTest.java
public static void main( String args[] )
{
LabelTest app = new LabelTest();

app.addWindowListener( new MyClose2() );

}
Using an Anonymous Class
• A common coding style is to subclass an
adapter class as an anonymous class inside
the program.

• This is the approach used in the original


LabelTest.java
• main() defines an anonymous class that
overrides windowAdapter

continued
• main() in LabelTest.java:
anonymous
class
public static void main( String args[] )
{
LabelTest app = new LabelTest();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{ System.exit( 0 ); }
}
);

continued
GUI Layout

• Objectives
– describe the basic layout managers for
GUIs
Contents
1. A Reminder on GUI Creation
2. Flow Layout
3. Grid Layout
4. Border Layout
5. Box Layout
6. Combining Layouts
1. Reminder on GUI Creation

• A reminder of the three steps in writing GUIs:


– 1. Declare the GUI controls;

– 2. Implement the event handlers for the controls;

– 3. Position the controls on the screen by using


layout managers and/or containers.
1.1. Emphasis of this Part
• The examples in this part will concentrate on
layout managers and the JPanel container
– step 3

• Layout managers examined:


– FlowLayout, GridLayout, BorderLayout,
BoxLayout, combining layouts
2. Flow Layout
• Components are added left-to-right
– they are centered in the container (frame/applet)
– a new line is started when necessary

• Resizing the frame/applet may cause


components to move to a new line.
FlowDemo.java
• import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FlowDemo extends JFrame


{
public FlowDemo()
{
super("E-Commerce Application");

Container c = getContentPane();
c.setLayout( new FlowLayout() );
:
JCheckBox jck1 =
new JCheckBox("Downgrade dog to cat");
JCheckBox jck2 =
new JCheckBox("Upgrade bike to car");
JCheckBox jck3 =
new JCheckBox("Add speed package");
c.add( jck1 ); c.add( jck2 );
c.add( jck3 );

JButton jb1 = new JButton("place order");


c.add( jb1 );
JButton jb2 = new JButton("cancel");
c.add( jb2 );

JLabel jl = new JLabel(new ImageIcon("bmw.jpg"));


c.add(jl);

setSize(400,200);
show();
} // end of FlowDemo()
public static void main(String[] args)
{
FlowDemo app = new FlowDemo();

app.addWindowListener( new WindowAdapter() {


public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
} // end of main()

} // end of FlowDemo
Initial Appearance
After Resizing

There is now space for all the


checkboxes and buttons on 1 line.
Notes
• By default, all the components on a line are
centered
– the alignment can be altered, e.g.
c.setLayout( new FlowLayout(
FlowLayout.RIGHT));
– there is also FlowLayout.LEFT

• The component sizes are unchanged


– this is not true of some other layout managers
3. Grid Layout
• GridLayout places components in a grid, specified
in terms of the number of rows and columns
– the spacing between the grid cells can also be specified

• The components are resized to fit the grid cell they


appear inside
– doesn't look nice

continued
• GridDemo.java contains one major change
from FlowDemo.java:
c.setLayout( new GridLayout(3,2,10,7);
– 3 rows, 2 columns, 10 pixel horizontal spacing,
7 pixel vertical spacing

• The other change is to increase the vertical size of


the frame:
setSize(400,400);
GridDemo.java
• import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GridDemo extends JFrame


{
public GridDemo()
{
super("E-Commerce Application");

Container c = getContentPane();
// use GridLayout: 3 rows, 2 columns
// 10 pixel horiz. gap, 7 pixel vert. gap
c.setLayout( new GridLayout(3, 2, 10, 7) );
:
JCheckBox jck1 =
new JCheckBox("Downgrade dog to cat");
JCheckBox jck2 =
new JCheckBox("Upgrade bike to car");
JCheckBox jck3 =
new JCheckBox("Add speed package");
c.add( jck1 ); c.add( jck2 ); c.add( jck3 );

JButton jb1 = new JButton("place order");


c.add( jb1 );
JButton jb2 = new JButton("cancel");
c.add( jb2 );

JLabel jl = new JLabel(new ImageIcon( bmw.jpg"));


c.add(jl);

setSize(400,400); // extra depth (200 --> 400)


show();
} // end of GridDemo()
public static void main(String[] args)
{
GridDemo app = new GridDemo();

app.addWindowListener( new WindowAdapter() {


public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
} // end of main()

} // end of GridDemo
Appearance
Components
have been
resized to
equally fill
the 400x400
space. Note the
horizontal
and vertical
spacing
between the
components.
GridDemoP.java
• Components can be protected from resizing
by being placed inside a JPanel
– the panel is resized instead

:
// use a panel to stop the cancel button growing
JPanel p = new JPanel();
JButton jb2 = new JButton("cancel");
p.add(jb2);
c.add( p );
:
Appearance

the 'cancel'
button has
not been
resized
4. Border Layout
• BorderLayout allows four components to be
placed around the edges of a frame/applet,
with a fifth component in the center
– the positions are "North", "East", "South",
"West", and "Center"

• BorderLayout is the default layout for


JFrame and JApplet
BorderDemo.java
• import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BorderDemo extends JFrame


{
public BorderDemo()
{
super("E-Commerce Application");

Container c = getContentPane();
// use BorderLayout:
// 10 pixel horiz. gap, 7 pixel vert. gap
c.setLayout( new BorderLayout(10, 7) );
:
// JCheckBox jck1 =
new JCheckBox("Downgrade dog to cat");
JCheckBox jck2 =
new JCheckBox("Upgrade bike to car");
JCheckBox jck3 =
new JCheckBox("Add speed package");
c.add( jck2, "East" );
c.add( jck3, "South" );

JButton jb1 = new JButton("place order");


c.add( jb1, "North" );
JButton jb2 = new JButton("cancel");
c.add( jb2, "West" );

JLabel jl = new JLabel(new ImageIcon("bmw.jpg"));


c.add(jl, "Center");

setSize(400,400); // extra depth (200 --> 400)


show();
// pack(); // get rid of excess space
} // end of BorderDemo()
public static void main(String[] args)
{
BorderDemo app = new BorderDemo();

app.addWindowListener( new WindowAdapter() {


public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
} // end of main()

} // end of BorderDemo
Appearance

Components
have been Note the
resized to vertical
fill the and
400x400 horizontal
space. spacing
between the
components
Component Resizing
• Components are resized:
– North and South are stretched to be as wide as
the window
– East and West are stretched to be tall enough to
touch the North and South components
– Center is enlarged to be as big as possible

• Often the look of the GUI can be improved


by calling pack() after show().
Appearance with pack()
The vertical
and horizontal
spacing
between the
components
is not affected.
More than Five?
• It is possible to have more than five
components in a GridLayout
– place them inside a JPanel (which can have
its own layout)
– the JPanel container can become one of the
components in the top-level frame/applet

• This use of JPanel is shown later.


Less than Five?
• If the grid does not have a component for a
given position, then the other components
are resized to fill the space.
– e.g. if North or South are not used, then East,
Center, and West will be made taller to fill the
space
5. Box Layout
• This places the components in a horizontal or
vertical sequence
– components are not resized

• BoxDemo.java places its components vertically


– aside from the layout manager, the code is very similar
to FlowDemo.java
– pack() can be used to reduce the window size
BoxDemo.java
• import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BoxDemo extends JFrame


{
public BoxDemo()
{
super("E-Commerce Application");

Container c = getContentPane();
// use BoxLayout: align components vertically
c.setLayout(
new BoxLayout(c, BoxLayout.Y_AXIS) );
:
JCheckBox jck1 =
new JCheckBox("Downgrade dog to cat");
JCheckBox jck2 =
new JCheckBox("Upgrade bike to car");
JCheckBox jck3 =
new JCheckBox("Add speed package");
c.add( jck1 ); c.add( jck2 ); c.add( jck3 );

JButton jb1 = new JButton("place order");


c.add( jb1 );
JButton jb2 = new JButton("cancel");
c.add( jb2 );

JLabel jl = new JLabel(new ImageIcon("bmw.jpg"));


c.add(jl);

setSize(400,400); // extra depth (200 --> 400)


show();
// pack(); // get rid of excess space
} // end of BoxDemo()
public static void main(String[] args)
{
BoxDemo app = new BoxDemo();

app.addWindowListener( new WindowAdapter() {


public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
} // end of main()

} // end of BoxDemo
Appearance
With pack()
6. Combining Layouts
• Real GUIs usually require several layout
managers for different parts of the display.

• The basic technique is to create panels (with


JPanel) to hold parts of the display
– each panel will have its own layout
– a panel may have subpanels
Example Appearance
Component Layout Hierarchy
frame
(border)

East West
Center

panel p1 panel p2
(vertical box) (vertical box)
image

check check check button button


box box box
CombinedDemo.java
• import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CombinedDemo extends JFrame


{
public CombinedDemo()
{
super("E-Commerce Application");

Container c = getContentPane();
// use default BorderLayout for frame
:
// panel 1: vertical box layout
JPanel p1 = new JPanel();
p1.setLayout(
new BoxLayout(p1, BoxLayout.Y_AXIS));
JCheckBox jck1 =
new JCheckBox("Downgrade dog to cat");
JCheckBox jck2 =
new JCheckBox("Upgrade bike to car");
JCheckBox jck3 =
new JCheckBox("Add speed package");
p1.add( jck1 );
p1.add( jck2 );
p1.add( jck3 );
:
// panel 2: vertical box layout
JPanel p2 = new JPanel();
p2.setLayout(
new BoxLayout(p2, BoxLayout.Y_AXIS));

JButton jb1 = new JButton("place order");


p2.add( jb1 );
JButton jb2 = new JButton("cancel");
p2.add( jb2 );
:
JLabel jl = new JLabel(
new ImageIcon( "bmw.jpg"));

// add panels and image to frame


c.add(jl, "Center");
c.add(p1, "West");
c.add(p2, "East");

setSize(400,400); // extra depth (200 --> 400)


show();
pack(); // remove excess space
} // end of CombinedDemo()
public static void main(String[] args)
{
CombinedDemo app = new CombinedDemo();

app.addWindowListener( new WindowAdapter() {


public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
} // end of main()

} // end of CombinedDemo
Multimedia

• Objectives
– introduce Java multimedia:
• images, audio, animations
Contents
1. Images
2. Audio
3. Animations
4. Animation Issues in AWT
5. Image Download Problem
6. Applet Parameters
7. Image Maps
8. Beyond Basic Multimedia
Loading Images
URL imageURL =
newURL("http://www.prenhall.com/logo.gif");
java.awt.Image img = this.getImage(imageURL);

You can compress this into one line as follows

Image img = this.getImage(new


URL("http://www.rss.gov.jo/logo.gif"));
Notes
• getDocumentBase()
– returns the location as a URL object
– can be on the Internet or in a local directory

• Graphics formats supported:


– GIF (Graphics Interchange Format)
• best for line drawings, black and white images
– JPEG (Joint Photographic Experts Group)
• best for full-colour photos
Retrieving an Image
• Both getImage() and ImageIcon() can
be passed URLs, to download an image
from the Web.

• Both methods return immediately, and they


download the image in a separate (hidden)
thread.
Drawing an Image
• g.drawImage(Image, X, Y, ImageObserver)

• g.drawImage(Image, X, Y, width, height,


ImageObserver)
– requires an ImageObserver object
ImageObserver
• The drawing of an image is controlled by an
ImageObserver object.
– the ImageObserver object updates the drawing of the
image as it is downloaded
– over the network, downloading may be slow which
means the image will appear bit-by-bit

– g.drawImage(logo1, 0, 0, this);
• this is the JApplet, an ImageObserver object that draws to
the screen
Drawing an ImageIcon
• ImageIcon.paintIcon(
Component-holding-the-image,
Graphics-object, X, Y)
– scaling is not possible
– no ImageObserver is needed
– ImageIcons can be converted to images (and
then scaled)
– over the network, downloading may be slow
which means the image will appear bit-by-bit
1. Images
• The tasks of LoadImageAndScale.java:
– draw three images in an applet
• an image, full-size and scaled
• an ImageIcon
1.1. Usage
Full-size
Image ImageIcon

Scaled
Image
1.2. LoadImageAndScale.java

• import java.applet.Applet;
import java.awt.*;
import javax.swing.*;

public class LoadImageAndScale extends JApplet {


private Image logo1;
private ImageIcon logo2;

public void init()


{
logo1 = getImage( getDocumentBase(),
"logo.gif" );
logo2 = new ImageIcon( "logo.gif" );
}
public void paint( Graphics g )
{
// draw the original image
g.drawImage( logo1, 0, 0, this );

// draw image scaled to fit width of applet


// and height of applet minus 120 pixels
g.drawImage( logo1, 0, 120,
getWidth(), getHeight() - 120, this );

// draw icon using its paintIcon method


logo2.paintIcon( this, g, 180, 0 );
}

} // end of LoadImageAndScale
LoadImageAndScale.html
• <html>
<applet code="LoadImageAndScale.class"
width=340 height=340>
</applet>
</html>
2. Audio
• Sounds can be played with the Applet play()
methods:
– load the sound, play it once only

• Methods:
– public void play(URL u, String fname);
– public void play(URL u);

continued
• For example:
play( getDocumentBase(), “hi.au”);
– play “hi.au” after loading it from the same
place as the Web page
2.1. AudioClip Sounds
• A more flexible way of playing sounds is to
use AudioClip methods.

• Methods for loading:


– public void getAudioClip(URL u, String fname);
– public void getAudioClip(URL u);

continued
• Methods for playing:
– public void play();
• play the audio clip once

– public void loop();


• play the audio clip repeatedly

– public void stop();


• stop playing the audio clip
2.2. Audio Example
• Load and play a AudioClip
– looping playing is possible
– playing can be stopped
Event Model
Play Loop Stop

currentSound

ItemStateChanged(...) {... }
anon. class

ActionPerformed(...) {... }
ButtonHandler
LoadAudioAndPlay.java
• // Load an audio clip and play it.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoadAudioAndPlay extends JApplet {


private AudioClip sound1, sound2, currentSound;
private JButton playSound, loopSound, stopSound;
private JComboBox chooseSound;

public void init()


{ Container c = getContentPane();
c.setLayout( new FlowLayout() );
String choices[] = { "Welcome", "Hi" };
chooseSound = new JComboBox( choices );
:
chooseSound.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
currentSound.stop();
currentSound =
chooseSound.getSelectedIndex() == 0 ?
sound1 : sound2;
}
} );
c.add( chooseSound );
:
ButtonHandler handler = new ButtonHandler();
playSound = new JButton( "Play" );
playSound.addActionListener( handler );
c.add( playSound );
loopSound = new JButton( "Loop" );
loopSound.addActionListener( handler );
c.add( loopSound );
stopSound = new JButton( "Stop" );
stopSound.addActionListener( handler );
c.add( stopSound );

sound1 = getAudioClip(
getDocumentBase(), "welcome.wav" );
sound2 = getAudioClip(
getDocumentBase(), "hi.au" );
currentSound = sound1;
} // end of init()
// stop sound when user switches Web pages
// (i.e., be polite to the user)
public void stop()
{ currentSound.stop(); }

private class ButtonHandler


implements ActionListener {
public void actionPerformed(ActionEvent e)
{ if ( e.getSource() == playSound )
currentSound.play();
else if ( e.getSource() == loopSound )
currentSound.loop();
else if ( e.getSource() == stopSound )
currentSound.stop();
}
} // end of ButtonHandler class

} // end of LoadAudioAndPlay class


LoadAudioAndPlay.html
• <html>
<applet code="LoadAudioAndPlay.class" width=350
height=50>
</applet>
</html>
2.3. Notes
• Audio formats supported:
– au (Sun Audio)
– wav (Windows Wave)
– aif / aiff (Macintosh AIFF)
– MIDI (Musical Instrument Digital Interface)
3. Animations
3.1. A Simple Animation
3.2. Event Model
3.3. Usage
3.4. Timers
3.5. LogoAnimator.java
3.6. Notes
3.1. A Simple Animation
• Load a series of ImageIcons into an array.

• Display the ImageIcons in a JPanel (acting


as a canvas)
– each image is displayed by redrawing JPanel
after incrementing an array index counter
– the redrawing freqency is controlled by a timer
3.2. Event Model

app
JFrame

paintComponent(...)
{ ... }

actionPerformed(...)
{ repaint();}

timer
LogoAnimator JPanel
3.3. Usage
3.4. Timers
• A Timer object can output ActionEvents at
regular time intervals
– these events will trigger actionPerformed()
in the specified object

• Setting a Timer
– Timer foo =
new Timer(frequency,
object-receiving-events);

continued
• foo.start(); // start the timer
• foo.stop(); // stop it
• foo.restart(); // restart after a stop
• foo.isRunning(); // boolean test
3.5. LogoAnimator.java
• // Animation a series of images
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LogoAnimator extends JPanel


implements ActionListener {
protected ImageIcon images[];
protected int totalImages = 30,
currentImage = 0,
animationDelay = 50; // ms delay
protected Timer animationTimer;
:
A 'problem' with
ImageIcon() is that
it returns before it
finishes loading.
public LogoAnimator()
{
setSize( getPreferredSize() );

images = new ImageIcon[ totalImages ];

// load the images into the array


for ( int i = 0; i < images.length; ++i )
images[ i ] =
new ImageIcon( "images/deitel" + i +
".gif" );

startAnimation();
}

continued
public void startAnimation()
{
if ( animationTimer == null ) {
currentImage = 0;
animationTimer =
new Timer( animationDelay, this );
animationTimer.start();
}
else // continue from last image displayed
// should not be used in this example
if ( ! animationTimer.isRunning() )
animationTimer.restart();
}

public void stopAnimation()


// not used in this example
{ animationTimer.stop(); }

continued
public void actionPerformed( ActionEvent e )
{ repaint(); }

public void paintComponent( Graphics g )


// redraw the panel
{
super.paintComponent( g );

if (images[currentImage].getImageLoadStatus()
== MediaTracker.COMPLETE ) {
images[currentImage].paintIcon(
this, g, 0, 0 );
currentImage = (currentImage + 1) %
totalImages;
}
} Check if the image has been loaded.

continued
public Dimension getMinimumSize()
{ return getPreferredSize(); }

public Dimension getPreferredSize()


{ return new Dimension( 160, 80 ); }

continued
public static void main( String args[] )
{
LogoAnimator anim = new LogoAnimator();

JFrame app = new JFrame( "Animator test" );


app.getContentPane().add( anim,
BorderLayout.CENTER );

app.addWindowListener( new WindowAdapter() {


public void windowClosing( WindowEvent e )
{ System.exit( 0 ); }
} );

app.setSize(
anim.getPreferredSize().width + 10,
anim.getPreferredSize().height + 30 );
app.show();
}
} // end of LogoAnimator
3.6. Notes
• Component Sizes
– JPanel (and other controls and components)
support the methods getMinimumSize() and
getPreferredSize()

– defining them allows the layout manager to


automatically obtain size information about the
component
paintComponent()
• paint() redraws a top-level container (e.g.
JFrame, JApplet)
• paintComponent() is used to redraw other
containers (e.g. JPanel)

• The programmer redefines paintComponent()


in the same way as paint()
– it will be called by repaint()

continued
• paintComponent()is redefined to paint an
ImageIcon from the array
– but only if the ImageIcon has been fully loaded
– if (images[currentImage].getImageLoadStatus()
== MediaTracker.COMPLETE ) {
...}
4. Beyond Basic Multimedia
• Some other Java Media APIs:
– Java 2D, Java 3D, Java Advanced Imaging,
Java Media Framework (JMF), Java Sound,
Java Speech

• More details:
– http://java.sun.com/products/
java-media/
4.1. JMF 2.1
• Capture, playback, transmit and translate audio,
video and other media

• Some supported formats:


– AVI, GSM, MPEG-1, QuickTime, RMF, RTP, Vivo,
etc.

• More details:
– http://java.sun.com/products/
java-media/jmf/index.html
4.2. Java Sound
• Provides low-level support for audio
operations such as audio mixing, audio
capture, MIDI sequencing, and MIDI
synthesis

• More details:
– http://java.sun.com/products/
java-media/sound/index.html
4.3. Java Speech (JSAPI)
• Specifies a cross-platform interface to support
speech recognizers, dictation systems, speech
synthesizers, etc.
• Related work:
– Java Speech API Markup Language (JSML)
– Java Speech API Grammar Format (JSGF)
• More details:
– http://java.sun.com/products/
java-media/speech/index.html
Input/Output

• Objectives
– discuss stream I/O in Java
Contents
1. Two Common Data Formats
2. Java I/O Essentials
3. Predefined Streams
4. Forms of Input
5. Forms of Output
1. Two Common Data Formats
• ASCII
– a 8-bit code (1 char = 1 byte)
– it can only represent 256 different chars

• Unicode
– a 16-bit code (1 char = 2 bytes)
– it can represent 65,536 different chars
• good for many non-English character sets
2. Java I/O Essentials
• All I/O in Java is done using streams.
• There are two kinds of streams:
– 8-bit streams, 16-bit streams
• The 8-bit streams are known as:
– InputStreams, OutputStreams
• The 16-bit streams are known as:
– Readers (for input), Writers (for output)
• Class names for I/O almost always contain the
words Reader, Writer, InputStream, or OutputStream
– this helps you identify what they can do
3. Predefined Streams
• System.in
– an InputStream used to read bytes from the
keyboard
• System.out
– a PrintStream used to write bytes to the
screen
• System.err
– a separate PrintStream (useful for redirection)
4. Forms of Input
• We will consider the following input
techniques:
– reading characters from the keyboard/file
– reading binary data from a file
– reading numbers and other types from the
keyboard
Classes for Input
• Data Format Class to use
ASCII / Unicode System.in (keyboard input)
FileReader (file input)
InputStreamReader
(byte stream, e.g. network)

Binary DataInputStream

Object ObjectInputStream
4.1. Reading Chars from the Keyboard

• The basic method is read() in System.in


– int read() throws IOException

– returns a unicode value, or -1 to signal end of


stream
– ASCII input is converted to Unicode
– read() must be in a try-catch block
Example: readin.java
import java.io.*;
public class readin
{
public static void main(String args[])
{ int i;
try {
while ( (i = System.in.read()) != -1 )
System.out.println( "read char: " +
(char) i +" hex value: " +Integer.toString(i,16));
}
catch (IOException ioe) {
System.out.println( "IO error:" + ioe );
}
}
} // end of readin class
Usage
I typed hello, enter,
then ctrl-Z
• C> java readin
hello
read char: h hex value: 68
read char: e hex value: 65
read char: l hex value: 6c
read char: l hex value: 6c
read char: o hex value: 6f
hex value: d
read char:
hex value: a
in Windows, enter
is represented by
C> carriage return ('\r'),
linefeed ('\n')
4.2. Reading Chars from a File
• The basic method is read() in FileReader
– int read() throws IOException

• The FileReader constructor takes the name of a file:


– FileReader fr =
new FileReader("filename");
– the file is automatically openned

• Files should be closed with close().


Example: fileread.java
• import java.io.*;
public class fileread {
public static void main(String args[])
{ int i;
int bytesRead = 0; It counts the
try {
FileReader fr = new number of bytes
FileReader("animals.txt");
while ( (i = fr.read()) != -1 )
bytesRead++;
fr.close();
}
catch (IOException ioe)
{ System.out.println( "IO error:" + ioe ); }
System.out.println("bytes read from file: "
+bytesRead);
}
}
Usage
• C> cat animals.txt
queenbee raven
swan terrier
urchin vixen
wallaby xoachi
yellowjacket zebra

• C> java fileread


bytes read from file: 77

C>
4.3. Reading from a Binary File
• DataInputStream is intended to read binary data from
a stream and return it in the specified data format.
• Some of its methods:
– boolean readBoolean()
– int readInt()
– float readFloat()
– byte readByte()
• Unlike read() in System.in and FileReader, the
methods do not return -1 at the end of the stream/file.
– instead an EOFException is raised
– your code must catch this in order to stop reading
• DataInputStream expects binary data
coming from a stream
– to read binary data from a file requires
stream layering with FileInputStream

FileInputStream DataInputStream int


Binary float
File bytes bytes etc.
from from a
a file stream
Example: readdata.java
• import java.io.*;
public class readdata
{
public static void main(String args[])
{
FileInputStream fis;
DataInputStream dis;
try {
fis = new FileInputStream( args[0] );
dis = new DataInputStream( fis );
System.out.println( "input file: " +
args[0] );
:
An infinite loop is the
common coding style
for binary stream input
int i;
while ( true ) { // eof is an exception
i = dis.readInt();
System.out.println( "read: " + i );
}
}
catch (EOFException eof)
{ System.out.println( "EOF reached " ); }
catch (IOException ioe)
{ System.out.println("IO error: " +ioe); }
}
This catch
} // end of readdata class block must
be coded.
5. Forms of Output
• We will consider the following output
techniques:
– writing data to the screen
– writing characters to a file
– formatted character output
– writing data to a binary file
Classes for Output
• Data Format Class to use
ASCII / Unicode System.out (screen output)
FileWriter (output to file)
OutputStreamWriter
(byte stream, e.g. network)

Binary DataOutputStream

Object ObjectOutputStream
Writing Data to the Screen / Writing
Chars to a File
• System.out.println(...)
System.out.print(...);
– they take a variety of data types, and output them as strings

• Use FileWriter methods:


– void write(String s);
void write(int i); etc.
void flush(); void close();

• The FileWriter constructor takes the name of a file:


– FileWriter fw =
new FileWriter("filename");
– the file is automatically openned
Example: filewrite.java
• import java.io.*;
public class filewrite
{
public static void main(String args[])
{ FileWriter fw;
int i;
try {
fw = new FileWriter( args[0] );
while ( (i = System.in.read()) != -1 )
fw.write( (char) i );
fw.close();
}
catch (IOException ioe)
{ System.out.println( "IO error:" + ioe
); }
}
}
Usage
• C> java filewrite foo.txt
hello
Daher
I typed this,
C> type foo.txt enter, and ctrl-Z
hello
Daher
C>
Writing to a Binary File
• DataOutputStream is intended to write data
to a binary stream.
• Some of its methods:
– void writeInt(int)
– void writeFloat(float)
– void writeBoolean(boolean)
– void writeByte(int)

continued
• DataInputStream streams can read anything
output by a DataOutputStream
• Layered streams are needed to connect a
DataOutputStream to a binary file.

FileOutputStream DataOutputStream int


Binary float
bytes bytes
File
to a file in a stream etc.
Example: writedata.java
• import java.io.*;
public class writedata {
public static void main(String args[])
{ FileOutputStream fos;
DataOutputStream ds;
try {
fos = new FileOutputStream(args[0]);
ds = new DataOutputStream( fos );
int a[] = {0,1,2,3,4,5,6,7,8,9};
for (int i=0; i<a.length; i++)
ds.writeInt(a[i]);
ds.close();
}
catch (IOException ioe)
{ System.out.println( "IO error: "+ioe); }
}
}
create the
Usage binary file
• C>java writedata numbers.txt

C>java readdata numbers.txt


input file: numbers.txt read it
read: 0 back in
read: 1
read: 2
read: 3
read: 4
read: 5
read: 6
read: 7
read: 8
read: 9
EOF reached

C>

You might also like