Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented...

61
Sept. 2003 Yangjun Chen 91.3 902 1 Java: Review Java J a v a b a s i c s A r t o f p r o g r a m m i n g O b j e c t - o r i e n t e d p r o g r a m m i n g A p p l e t s a n d g r a p h i c s I n t r o d u c t i o n

Transcript of Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented...

Page 1: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 1

Java: Review

Java

Java basics

Art of program

ming

Object-oriented program

ming

Ap p le ts a nd g r ap h ic s

Introduction

Page 2: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 2

Java: Review

Introduction

What is Java?

object-oriented language

platform independent

- JVM

- two-phase execution

Multi-threaded

HelloWorld program

Page 3: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 3

Java: Review

Java basics

Java basics I

Java basics II

Page 4: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 4

Java: Review

Basics -I

• Basic concepts:class declarationclass body, methodsvariablesidentifierscomments

• Primitive data types• Operators

arithmetic operatorslogic operatorsbitwise operators

Page 5: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 5

Java: Review

•The modulus (%) operator gives the remainder after integer division: 31%9 = 4.

-5%3 = -2

5%-3 = 2

- 5%-3 = -2

Page 6: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 6

Java: Review

Type Casting• Example:

class GoodAssignment {public static void main(String args[]) {

byte b;int i=127;b=(byte) i;System.out.println(b); //display

127}}

class GoodAssignment {public static void main(String args[]) {

byte b;int i=258;b=(byte) i;System.out.println(b); //display 2}}

0 011 0... ...

8 bits

16 bits

Page 7: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 7

Java: Review

Bitwise OperatorsBitwise Operators• Number can be represented by a set of bits (a series of 0s and

1s)• Binary digits take on the value of 0 or 1.• Example:

the binary number (110101)2 represents the decimal number 53.

Operator Meaning& AND| OR^ XOR~ Bitwise complement>> Shift right with sign extension>>> Shift right with zero fill<< Shift left with zero fill

Page 8: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 8

Java: Review

Bitwise OperatorsBitwise Operators110101101010

100000

&110101101010

111111 |

110101^ 101010

011111

110101 111010>>

110101 011010>>>

110101 101010<<

|

Page 9: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 9

Java: Review

import java.lang.*;//bit operationspublic class ShowBits {

public static void main(String args[]){byte b = -5; for (int i = 7; i>=0; i--) { if ((b & 0x80) == 0)

System.out.println("bit " + i + "is 0"); else System.out.println("bit " + i + "is 1"); b <<= 1; }}

}

Page 10: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 10

Java: Review

Java Basics - IIJava Basics - II• Modifiers (Specifiers)• Statements• Array• Control flow

- condition statements:ifswitch

- loop structure:forwhiledo

• others: String, print, new, constructor

Page 11: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 11

Java: Review

ModifiersModifiers• Modifiers are special keywords that modify the definition of a

class, method, or variables.

modifiers

Modifiersfor methods

Modifiersfor variables

Modifiersfor classes

Page 12: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 12

Java: Review

Modifiers for Methods and VariablesModifiers for Methods and Variables

• static• final• private• protected• public

access modifiers

Page 13: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 13

Java: Review

Modifiers for ClassesModifiers for Classes

• There are three modifiers for classes in Java.- public

This makes a class accessible to outside of the package.- final

This prevents a class from being extended.- abstract

In an abstract class, some abstract methods (with only method signature; no implementation) are defined. Therefore, an abstract

class can not be instantiated.

Page 14: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 14

Java: Review

Art of programming

Computing factorials

- simple

- recursive

- cacheSorting

- simple- Quick sorting- Merge sorting

Computing primes

Page 15: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 15

Java: Review

Computing FactorialsComputing Factorials

• Recursive Factorials

public class Factorial2 {public static long factorial(long x) {

if (x == 1) return 1;else return x*factorial(x - 1);

}}

public class ComputingFactorial {public static void main(String arg[]) {

int a = Factorial.factorial2(Integer.parseInt(arg[0]));System.out.println(a);}}

Page 16: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 16

Java: Review

Computing FactorialsComputing Factorials

• Caching factorials

public class Factorial3 {//create an array to cache values 0! Through 20!Static long[] table = new long[21];Static {table[0] = 1;} //factorial of 0 is 1//Remember the highest initialized value in the array

static int last = 0; public static long factorial(int x) {

while (last < x) {table [last + 1] = table[last]*(last + 1);last++;

}}

Page 17: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 17

Java: Review

Sorting NumbersSorting Numbers

main idea:

1st step: 3 1 6 5 4 8 10 7

2nd step: 3 2 1 5 8 9 10 7

3rd step: 3 2 1 4 5 6 8 9 10 7

center to

2299

66 44

Smaller than 5Smaller than 5 greater than 5greater than 5

i j

The center element is 5.

i = j = 5

• Quick sort

from

Page 18: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 18

Java: Review

Sorting NumbersSorting Numbers

4th step: 4 5 6 10

5th step: 1 2 3 4

centerfrom to

33 77

tofrom center

i = 2

j = 2

8 92 1

Page 19: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 19

Java: Review

6th step: 16th step: 1

The sequence contains only one element, no sorting.

7th step: 3 47th step: 3 4

i = j = 1

8th step: 8th step: 4 4

from tocenter

The center element is 4.

The sequence contains only one element, no sorting.

1 2 3 4 51 2 3 4 5

Page 20: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 20

Java: Review

18,

19,

18,

3, 4, 6, 1, 10, 9, 5, 20, 19, 18, 17, 2, 1, 14, 13, 12, 11, 8, 16, 15

3, 4, 6, 1, 10, 9, 5, 15, 19, 17, 2, 1, 14, 13, 12, 11, 8, 16, 20

18,16,3, 4, 6, 1, 10, 9, 5, 15, 17, 2, 1, 14, 13, 12, 11, 8, 20

3, 4, 6, 1, 10, 9, 5, 15, 16, 8, 17, 2, 1, 14, 13, 12, 11, 19, 20

i=17

j=16

3, 4, 6, 1, 10, 9, 5, 15, 16, 8, 17, 2, 1, 14, 13, 12, 11

Sorting NumbersSorting Numbers

ii jj

• Quick sort

Page 21: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 21

Java: Review

• Another Java program for the quick sort:

public class Sorter {public static void sort (int[] a, int from, int to) {

if ((a == null) || (a.length < 2)) return;int i = from -1, j = to + 1;int center = a[(from + to)/2];do {i++; j--;

while ((i < to) && (a[i] < center)) i++;while ((j > from) && (a[j] > center)) j--;if (i < j) { int tmp =a[i]; a [i] = a[j]; a[j] = tmp;}}while (i <= j);

if (from < j) sort(a, from, j);if (i < to) sort(a, i, to);

}}

Page 22: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 22

Java: Review

import java.lang.*;public class sort {

public static void sort (int[] a, int from, int to) {int tag = 0; if ((a == null) || (a.length < 2)) return;int i = from, j = to;int center = a[(from + to)/2];do { while ((i < to) && (a[i] < center)) i++; while ((j > from) && (a[j] > center)) j--; if (j > i) tag = 1; else if (j == i) tag = 0;

else tag = -1;

Page 23: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 23

Java: Review

switch (tag) {case 1:

int tmp =a[i]; a [i] = a[j]; a[j] = tmp; i++; j--; break;

case 0: i++; j--; break;default:}

}while (i <= j); if (from < j) sort(a, from, j); if (i < to) sort(a, i, to);}

Page 24: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 24

Java: Review

public static void main(String args[]) {int array[]=new int[20];for(int i = 0; i < 20; i++) //Generate random numbers array[i] = (int)(Math.random()*100); sort(array,0,19); System.out.println("the final answer is:"); for (int i=0;i<array.length;i++) System.out.print(array[i]+" "); }

}

Page 25: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 25

Java: Review

•Sorting by merging

Merging means the combination of two or more ordered sequence into

a single sequence. For example, can merge two sequences: 503, 703, 765

and 087, 512, 677 to obtain a sequence: 087, 503, 512, 677, 703, 765.

A simple way to accomplish this is to compare the two smallest items,

output the smallest, and then repeat the same process.

503 703 765087 512 677 087

503 703 765512 677

087 503703 765512 677

Page 26: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 26

Java: Review

•Merging algorithm

Algorithm Merge(s1, s2)Input: two sequences: s1 - x1 x2 ... xm and s2 - y1 y2 ... yn

Output: a sorted sequence: z1 z2 ... zm+n.1.[initialize] i := 1, j := 1, k := 1;2.[find smaller] if xi yj goto step 3, otherwise goto step 5;3.[output xi] zk.:= xi, k := k+1, i := i+1. If i m, goto step 2;4.[transmit yj ... yn] zk, ..., zm+n := yj, ..., yn. Terminate the

algorithm;5.[output yj] zk.:= yj, k := k+1, j := j+1. If j n, goto step 2;6.[transmit xi ... xm] zk, ..., zm+n := xi, ..., xm. Terminate the

algorithm;

Page 27: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 27

Java: Review

- Merge-sorting

Algorithm Merge-sorting(s)

Input: a sequences s = < x1, ..., xm>Output: a sorted sequence.1. If |s| = 1, then return s;2. k := m/2;3. s1 := Merge-sorting(x1, ..., xk);4. s2 := Merge-sorting(xk+1, ..., xm);5. return(Merge(s1, s2));

Page 28: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 28

Java: Review

Computing PrimesComputing Primes

• Finding the largest prime number smaller than a specified integer:Input integer m, find p m such that p is a prime and if there is prime p’ > p then p’ must be larger m.

than m.11 22 4433 55 7766 88 99 1212 1414 1515 1616 1818 20201010 1111 1313 1717 1919

Page 29: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 29

Java: Review

Computing PrimesComputing Primes

Import java.lang.*;

public class Sieve {public static void main(String[] args) {

int max = 100; //Assign a default valuetry {max = Integer.parseInt(args[0]);}catch (Exception e) {} //Silently ignore exceptions.

//Create an array that specifies whether each number is prime or not.boolean[] isprime = new boolean[max+1];

//Assume that all numbers are primes, until proven otherwise.for (int i = 0; < max; i++) isprime[i] = true;

//We know that that 0 and 1 are not prime. Make a note of it.isprime[0] = isprime[1] = false;

Page 30: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 30

Java: Review

Computing PrimesComputing Primes

//To compute all primes less than max, we need to rule out multiples of all//integers less than the square root of max.

int n = (int) Math.ceil(Math.sqrt(max));

for (int i = 0; i <= n; i++) {if (isprime[i]) { int k = 2;

for (int j = k*i; j < max; j = (k ++)*i) isprime[j] = false; }

}

int largest;for (largest = max - 1; !isprime[largest]; largest--); //empty loop bodySystem.out.println(“The largest prime less than or equal to “ + max + “is ”

+ largest); }}

Page 31: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 31

Java: Review

Object-oriented programming

What is OOP?

Class, instance, field, method, ...

“this” key word

Method Overloading

Inheritance

Method Overriding

Abstract and Interface

Page 32: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 32

Java: Review

What is OOP?

• Procedural programming is where you would try to solve a problem using pre-determined types: int, floats, strings and arrays.

• In OOP, you create a model that best represents the problem.• The programmer defined model is known a class.• A class is a programmer defined type, together with a lot of

procedures manipulating over it. Such a type can be used as template for instance of the class.

Page 33: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 33

Java: Review

“this” in Constructors (Example for Method Overloading)

• To invoke a constructor from another constructor in the same class:class Car { String licensePlate; double speed, maxSpeed;

public Car(String licensePlate, double speed, double maxSpeed) {this.licensePalte = licensePlate;this.speed = speed;this.maxSpeed = maxSpeed;

}public Car(String licensePlate, double maxSpeed) {

this(licensePlate, 0.0, maxSpeed); }void accTomax ( ) { … } void accelerate ( ) {…}

}

Page 34: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 34

Java: Review

Interfaceimport java.util.*;import java.lang.*;

interface CanFight { void fight ( );}interface CanSwim { void swim ( );}interface CanFly {void fly ( );}

class ActionCharacter { public void fight( ) { }}class Hero extends ActionCharacter

implements CanFight, CanSwim, CanFly {public void fight ( ) {System.out.println(“Can fight!”);}public void swim ( ) {System.out.println(“Can swim!”); }public void fly ( ) {System.out.println(“Can fly!”);}

}

Page 35: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 35

Java: Review

Interface

public class Adventure {static void t(CanFight x) { x.fight();}static void u(CanSwim x) { x.swim();}static void v(CanFly x) { x.fly();}static void w(ActionCharacter x) { x.fight();}public static void main (String[ ] args) {

Hero h = new Hero( );t(h); //Treat it as a CanFightu(h); //Treat it as a CanSwimv(h); //Treat it as a CanFlyw(h); //Treat it as an ActionCharacter

} }

Page 36: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 36

Java: Review

Upcasting and Polymorphism

• Upcasting: Taking an object reference and treating it as a reference to its base type is called upcasting, because of the way inheritance trees are drawn with the base class at the top.

class Note { private int value; private Note(int val) {value = val;} public static final Note

middle_c = new Note(0),c_sharp = new Note(1),b_flat = new Note(2);

}

Page 37: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 37

Java: Review

Upcasting and Polymorphism

class Instrument { public void play(Note n) {

System.out.println(“Instrument.play()”) }}

class Wind extends Instrument { public void play(Note n) {

System.out.println(“Wind.play()”); }}

Instrument

Wind

Page 38: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 38

Java: Review

Upcasting and Polymorphism

public class Music { public static void tune(Instrument i) {

// …i.play(Note.middle_c);

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

Wind flute = new Wind();tune(flute); //Upcasting

}}

Page 39: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 39

Java: Review

Upcasting and Polymorphism

• Polymorphism: In Java, the principle that the actual type of the object determines the method to be called is called polymorphism.class Shape { void draw() {} void erase() {}}

class Circle extends Shape { void draw() {

System.out.println(“Circle.draw()”); } void erase() {System.out.println(“Circle.erase()”);}}

Shape

draw()erase()

Squaredraw()erase()

Triangledraw()erase()

Circledraw()erase()

Page 40: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 40

Java: Review

class Square extends Shape { void draw() {

System.out.println(“Square.draw()”); } void erase() {System.out.println(“Square.erase()”);}}

class Triangle extends Shape { void draw() {

System.out.println(“Triangle.draw()”); } void erase() {System.out.println(“Triangle.erase()”);}}

Upcasting and Polymorphism

Page 41: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 41

Java: Review

public class Shapes { public static Shape randShape() {

switch((int) (Math.random()*3)) {case 0: return new Circle();case 1: return new Square();case 2: return new Triangle();default : return new Circle();}}

public static void main(String[] args) { Shape[] s = new Shape[9]; for (int i = 0; i < s.length; i++)

s[i] = randShape(); //Make polymorphism method calls: for (int i = 0; i < s.length; i++) s[i].draw();}}

Upcasting and Polymorphism

Page 42: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 42

Java: Review

Applets and graphics

• Applet- HelloWorld Applet

- import statement- Hypertext Mark Language (HTML)

• Graphic- line- rectangle- polygon- ovals- arcs- color- font

Page 43: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 43

Java: Review

Applets

• There are two types of Java programs:- Applications and Applets

• An applet is a subclass of Applet class defined in “applet” package.

• Using appletviewer to run a HTML file that contains an applet class; or invoke it through an internet browser.

appletviewer HelloWorld.htmlorinput the URL address of your HTML file by internet explorer: H:\javaprog\EventTest1.html

Page 44: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 44

Java: Review

HelloWorld Applet

• The HelloWorld applet:

import java. applet.*;import java. awt.*;// A simple Java Appletpublic class HelloWorld extends Applet

{public void paint( Graphics g)

{g. drawString(“ HelloWorld!”, 20,10);

}}

Page 45: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 45

Java: Review

HelloWorld Applet• HelloWorld.html:

<HTML><BODY><APPLET CODE = HelloWorld.class

WIDTH = 200 HEIGHT=200>

</ APPLET></BODY></HTML>

URL address: file://e:/javaprog/HelloWorld.html

Page 46: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 46

Java: Review

Life Cycle of an Applet• An Applet executes within an environment

provided by a Web browser or a tool such as the applet viewer.

• It does not have a main() method• There are four methods that are called during the

life cycle of an applet:init(),start(),stop(),destroy().

Page 47: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 47

Java: Review

import Statements• import statements must appear before any of the

namesdefined in the import are used.

• It is a strong recommendation that all imports appear at thebeginning of your program.

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

• Package construction:- Assume that there are classes in D:\ychen2\javaprog- The first statement in each class: package javaprog- in D:\ychen2, issue command: javac javaprog\*.java- set classpath = %classpath%;D:\ychen2

Page 48: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 48

Java: Review

Graphics• The java. awt package contains all the necessary

classesyou need to create graphical user interfaces

(GUIs).• Most of the graphics operations in Java are

methodsdefined in the Graphics class.

• You don’t have to create an instance of the Graphics classbecause in the applet’s paint() method, a Graphics

object isprovided for you. By drawing in that object, you

drawonto your applet which appears on the screen.

• The Graphics class is part of the java.awt package, somake sure you import it into your Java code.- import java. awt. Graphics;

Page 49: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 49

Java: Review

The Coordinate System• Java’s coordinate system has the origin (0,0) in the

top leftcorner of the applet.- Positive x values are to the right and positive y values are

downward• The coordinate system is represented by pixels.

- Pixels in Java are integer values only(0,0)

(60,50)

+X

+Y

(20,20)

Page 50: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 50

Java: Review

Lines• To draw a line onto the screen, use the drawLine()

method:- void drawLine( int x1, int y1, int x2, int y2);- This draws a line from the point with coordinates (x1, y1)

to thepoint with coordinates (x2, y2).

- Example:import java. awt. Graphics;public class MyLine extends java. applet. Applet {

public void paint( Graphics g) {g. drawLine( 25,25, 75,75);

}}

- There is no way to change the line thickness in Java.So how do we make thicker lines?

Page 51: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 51

Java: Review

Rectangles• To draw a rectangle on the screen, use the

drawRect()method:- void drawRect( int x, int y, int width, int height)

• Example:import java. awt. *;public class MyRect extends java. applet. Applet {

public void paint( Graphics g) {g. drawRect(120,20, 60,60);g. setColor( Color. red);g. fillRect( 120, 20,60, 60);

}}

Page 52: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 52

Java: Review

Rounded Rectangles• These are rectangles with the corners rounded

according tothe values of the arguments.

• Like the rectangle, there are two methods for roundrectangles:- void drawRoundRect( int x, int y, int width, int height, int

arcWidth, int arcHeight)- void fillRoundRect( int x, int y, int width, int height, int arcWidth,

int arcHeight)

Page 53: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 53

Java: Review

3D Rectangles• You can also draw three dimensional rectangles in

Java- Warning: They really don’t look too good though

• There are two methods as well:- void draw3DRect( int x, int y, int width, int height, boolean raised)- void fill3DRect( int x, int y, int width, int height, boolean raised)- The argument “raised”, when true, will paint the rectangle as if it

were raised from the surface.- If it is false, the rectangle will appear as if it were

depressed.

Page 54: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 54

Java: Review

Polygons• Polygons are shapes with an unlimited # of sides.• To draw a polygon, you need a set of x and y

coordinates.• The polygon is then drawn by drawing a series of

straightlines from the first point to the second, to the

third and soon.import java. awt. Graphics;

public class MyPolygon extends java. applet. Applet {public void paint( Graphics g) {

int exes[]={ 39, 94,97, 142,53, 58,26};int whys[]={ 33,74, 36,70,108,80,106};int pts= exes. length;g. drawPolygon( exes, whys, pts);

}}

Page 55: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 55

Java: Review

Polygons using the Polygon Class• Example:

import java. awt. Graphics;import java. awt. Polygon;public class MyPolygon2 extends java. applet. Applet {

public void paint( Graphics g) {int exes[]={ 39, 94,97, 142,53, 58,26};int whys[]={ 33,74, 36,70,108,80,106};int pts= exes. length;Polygon poly= new Polygon( exes, whys, pts);g.drawPolygon(poly);g.fillPolygon( poly);

}}

Page 56: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 56

Java: Review

Ovals• Ovals are drawn with the drawOval() or fillOval()

methods- void drawOval( int x, int y, int width, int height)- void fillOval( int x, int y, int width, int height)- This draws an oval within the bounding rectangle

specified by thearguments

- Example:import java. awt. Graphics;public class MyOval extends java. applet. Applet {

public void paint( Graphics g) {g. drawOval( 20, 20, 60,60);g. fillOval( 120, 20,60,60);

}}

Page 57: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 57

Java: Review

Arcs• An arc is basically part of an oval.• Arcs are drawn using the method:—

- void drawArc( int x, int y, int width, int height, int startAngle, int arcAngle)

- void fillArc( int x, int y, int width, int height, int startAngle, intarcAngle)

- This draws an arc within the rectangle specified starting from the

startAngle argument for a duration of arcAngle.- Example:

g. drawArc( 10,10,100,80,45,210);

Page 58: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 58

Java: Review

Arcs• Example:

import java. awt. Graphics;public class MyArc extends java. applet. Applet {

public void paint( Graphics g) {g. drawArc( 120,20, 60,60,90, 180);g. fillArc( 120,20,60, 60,90,180);

}}

Page 59: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 59

Java: Review

The Color Class• This class contains 13 constant values that can be

used:- black, blue, cyan, darkGray, Gray, green, lightGray, magenta,

orange, pink, red, white, yellow• To address them we have to reference them

through theColor class- eg. Color. black- Too set the current color to blue:

g. setColor(Color. blue)• Colors in Java are described by the RGB (Red,

Green,Blue) model.- This model specifies the amount of red, green, and blue

in a color.- The intensity of each component is measured as an

integer between0 and 255, with 0 representing no light.

(0,0,0) is black(128,128,128) is medium gray

Page 60: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 60

Java: Review

The Color Class

• To declare a new color in Java, use the “new” operator- Color myColor = new Color( 255, 0, 128);- We now have a new color and since we know it is an

object of the Color class we can use it directlyg. setColor(myColor);

- You can also define the color “on the fly” or in line with the

setColor() methodg. setColor( new Color( 255,0,128));

Page 61: Java: Review Sept. 2003Yangjun Chen 91.39021 Java Java basics Art of programming Object-oriented programming Applets and graphics Introduction.

Sept. 2003 Yangjun Chen 91.3902 61

Java: Review

The Font Class• There are five basic fonts in Java

- SanSerif (Helvetica), Serif (Times Roman), Monospaced (Courier),Dialog, DialogInput

• There are some constant values associated with the Font classas well.- Font.BOLD, Font.PLAIN, Font.ITALIC

• Create a Font object by using the “new” operator- Font myFont = new Font(“Helvetica”, Font.BOLD, 12);

- After creating a font, you have to set it before it can be used:g.setFont(myFont);

- You can also do this in line with the setFont() methodg.setFont(new Font(“Helvetica”, Font.BOLD, 12));

• You can also combine styles by adding them together, forexample

Font myFont = new Font(“Helvetica”, Font.BOLD+ Font.ITALIC, 12)