| PUSAT SKRIPSI DAN ARTIKEL2 java

(1)

Software Design

Introduction to the

Java Programming Language


(2)

Java Features

• “Write Once, Run Anywhere.”

• Portability is possible because of Java virtual machine technology:

– Interpreted

– JIT Compilers

• Similar to C++, but “cleaner”:

– No pointers, typedef, preprocessor, structs,

unions, multiple inheritance, goto, operator overloading, automatic coercions, free.


(3)

Java Subset for this Course

• We will focus on a subset of the language that will allow us to develop a distributed application using CORBA.

• Input and output will be character (terminal) based.

• For detailed treatment of Java visit:


(4)

Java Virtual Machine

• Java programs run on a Java Virtual Machine.

• Features:

– Security

– Portability

– Superior dynamic resource management

– Resource location transparency


(5)

The Java Environment

Java Source File (*.java)

Java Compiler (javac)

Java Bytecode File (*.class)


(6)

Program Organization

Source Files (.java)

JAVA BYTECODE

COMPILER

Class Files (.class) Running

Application JAVA VIRTUAL MACHINE Running


(7)

Program Organization Standards

• Each class is implemented in its own source file.

• Include one class per file:

– Name of the Java file is the same as the class name.

• Java applications must include a class with a

main method. E.g.,


(8)

Structure of a simple Java

Program

• Everything must be in a class.

• Java applications (not Applets) must have a

main() routine in one of the classes with the signature:

public st at ic void main(St r ing [] ar gs) class HelloW or ld

{

public st at ic void main(St r ing [] args) {

Syst em. out . print ln(“Hello W orld!”); }


(9)

Compiling and Running

the“Hello World” Program

• Compile:

– j avac HelloW or ld.j ava

• Run:

– j ava HelloW or ld

• Output:


(10)

Comments

• Java support 2 commenting styles

/ / Line Comment s


(11)

Data Types

• Basic types:

– byte, boolean, char, short, int, long, float, double.

– New types cannot be created in Java. Must create

a Java class.

• Java arrays are supported as classes. E.g.,

int [] i = new int [9]


(12)

Scalar Data Types In Java

• Standard Java data types:

– byt e 1 byte

– boolean 1 byte

– char 2 byte (Unicode)

– shor t 2 byte

– int 4 byte

– long 8 byte

– f loat 4 byte

– double 8 byte

<dat a t ype> var iable_name; int x;


(13)

Java is Strongly Typed

• Java is a strongly typed language.

• Strong typing reduces many common programming errors.

• Seems inconvenient to C/C++ programmers.


(14)

Java is Strongly Typed (Cont’d)

• Assignments must be made to compatible data types.

• To contrast, in C:

– No difference between int , char , and “boolean”

– Implicit type casts (automatic type promotion)


(15)

Variables

• Variables may be tagged as constants (f inal

keyword).

• Variables may be initialized at creation time

f inal variables must be initialized at creation time

• Objects are variables in Java and must be

dynamically allocated with the new keyword.

E.g., a = new ClassA();

• Objects are freed by assigning them to null, or when

they go out of scope (automatic garbage collection). – E.g., a = null;


(16)

Variables (Cont’d)

int n = 1;

char ch = ‘A’;

St r ing s = “Hello”;

Long L = new Long(100000); boolean done = f alse;

f inal double pi = 3. 14159265358979323846; Employee j oe = new Employee();

char [] a = new char[3]; Vect or v = new Vect or();


(17)

Pointers & References Variables

• Java does not support pointers.

• All variables are passed by value except objects.

• Java classes either:

– Reference an object (new keyword)


(18)

Expressions

• Java supports many ways to construct expressions (in precedence order):

– ++,-- Auto increment/decrement

– +,- Unary plus/minus

– *,/ Multiplication/division

– % Modulus


(19)

Examples of Expressions

int x, y, z;

x = 0; x++;

y = x + 10; y = y % 5; z = 9 / 5;


(20)

Assignment Operators

• Assignment may be simple

– x = y

• Or fancy with the following operators:

– *=, /=

– %=

– +=, -=

– &= (bitwise AND)

– |= (bitwise OR)


(21)

Examples of

Assignment Operators

int i = 5;

i += 10; / / i = 15 i %= 12; / / i = 3


(22)

Conditional Logic

• Conditional logic in Java is performed with the

if statement.

• Unlike C++ a logic expression does not

evaluate to 0 (FALSE) and non-0 (TRUE), it evaluates to either t r ue or f alse

t r ue, f alse are values of the boolean data type.

• Building compound conditional statements


(23)

Example of Conditional Logic

int i = 8;

if ((i >= 0) && (i < 10))

Syst em. out . print ln(i + “ is bet ween 0 and 9”); else


(24)

Code Blocks

• Java, like many other languages, allows compound code blocks to be constructed from simple statements.

• Simply enclose the block of statements between braces. E.g.,

{

St at ement 1; St at ement 2; St at ement 3; }


(25)

Looping Constructs

• Java supports three looping constructs:

while

do. . . while


(26)

Examples of Looping Constructs

f or (int i = 0; i < 10; i++) {

Syst em. out . print ln(i); }

int i = 0; while(i < 10) {

Syst em. out . print ln(i++); / / print s i bef ore

} / / applying i++

int i = 0; do

{

Syst em. out . print ln(i++); } while(i < 10)


(27)

Java Exception Handling

• An exception is an object that defines an unusual or erroneous situation.

• An exception is thrown by a program or a runtime

environment and can be caught and handled

appropriately.

• Java supports user-defined and predefined

exceptions:

– ArithmeticException

– ArrayIndexOutOfBoundsException

– FileNotFoundException


(28)

Java Exception Handling (Cont’d)

• Exception handling allows a programmer to divide a program into a normal execution flow and an exception execution flow.

• Separation is a good idea especially since 80% of execution is in 20% of the code (normal flow).


(29)

Java Exception Handling (Cont’d)

• If an exception is not handled the program will terminate (abnormally) and produce a message.

public class DivideBy0 {

public st at ic void main (St r ing[ ] ar gs) { Syst em.out .pr int ln(10 / 0);

} }

J ava.lang.Ar it hmet icExcept ion: / by zer o at DivdeBy0.main(DivdeBy0:3)


(30)

Try

and

Catch

statements

• If an exception is thrown in statement-list1,

control is transferred to the appropriate (with same exception class) catch handler.

• After executing the statements in the catch clause,

control transfers to the statement after the entire try statement.

t r y {

st at ement -list 1

} cat ch (except ion-class1 var iable1) { st at ement -list 2

} cat ch (except ion-class2 var iable2) { st at ement -list 3


(31)

Exception Propagation

• If an exception is not caught and handled where it occurs, it propagates to the calling method.


(32)

class Demo {

st at ic public void main (St r ing[] ar gs) {

Except ion_Scope demo = new Except ion_Scope(); Syst em.out .pr int ln(“Pr ogr am beginning”);

demo.L1( );

Syst em.out .pr int ln(“Pr ogr am ending”); }

}

class Except ion_Scope { public void L3 ( ) {

Syst em.out .pr int ln(“Level3 beginning”); Syst em.out .pr int ln(10/ 0);

Syst em.out .pr int ln(“Level3 ending”); }

public void L2 ( ) {

Syst em.out .pr int ln(“Level2 beginning”); L3( );

Syst em.out .pr int ln(“Level2 ending”); }

public void L1 ( ) {

Syst em.out .pr int ln(“Level1 beginning”); t r y { L2 ();

} cat ch (Ar it hmet icExcept ion pr oblem) {

Syst em.out .pr int ln(pr oblem.get Message( )); pr oblem.pr int St ackTr ace ( );

}

Syst em.out .pr int ln(“Level1 ending”); } } OUTPUT: OUTPUT: Program beginning Level1 beginning Level2 beginning Level3 beginning / by zero

Java.lang.ArithmeticException: / by zero at Exception_Scope.L3(Demo.java:18) at Exception_Scope.L2(Demo.java:24) at Exception_Scope.L1(Demo.java:31) at Exception_Demo.main(Demo.java:7) Level1 ending Program ending


(33)

Throwing an Exception

impor t j ava.io.I OExcept ion;

public class Demo {

public st at ic void main (St r ing[ ] ar gs) t hr ows Doh { Doh pr oblem = new Doh (“Doh!”);

t hr ow pr oblem;

/ / Syst em.out .pr int ln(“Dead code”); }

}

class Doh ext ends I OExcept ion { Doh (St r ing message) {

super (message); }

}

• The exception is thrown but not caught.

OUTPUT:

OUTPUT:

Doh: Doh!


(34)

Finally

clause

• A try statement may have a finally clause.

• The finally clause defines a section of code

that is executed regardless of how the try

block in executed.

t r y {

st at ement -list 1

} cat ch (except ion-class1 var iable1) { st at ement -list 2

} cat ch …

} f inally {

st at ement -list 3 }


(35)

I/O

• Java supports a rich set of I/O libraries:

– Network

– File

– Screen (Terminal, Windows, Xterm)

– Screen Layout


(36)

I/O (Cont’d)

• For this course we only need to write to or read from the terminal screen or file.

• Use:

Syst em. out . pr int ln()

Syst em. out . pr int ()

• May use ‘+’ to concatenate

int i, j ; i = 1; j = 7;


(37)

I/O Example with Reading and

Writing from or to the Screen

import j ava. io. * ;

public class X {

public st at ic void main(St ring args[]) {

t r y{

Buf f er edReader dis = new Buf f er edReader ( new I nput St reamReader (Syst em. in)); Syst em. out . pr int ln("Ent er x ");

St r ing s = dis. r eadLine();

double x= Double. valueOf (s. t r im()). doubleValue();

/ / t rim r emoves leading/ t r ailing whit espace and ASCI I cont r ol char s. Syst em. out . pr int ln("x = " + x);

} cat ch (Except ion e) {

Syst em. out . pr int ln("ERROR : " + e) ; e. print St ackTr ace(Syst em. out );


(38)

I/O Example with Reading and

Writing from or to the File

import j ava. io. * ; import j ava. ut il. * ;

/ / Program t hat reads f rom a f ile wit h space delimit ed name- pairs and / / wr it es t o anot her f ile t he same name- pair s delimit ed by a t ab.

class P {

public st at ic void main(St ring [] args) {

Buf f eredReader reader_d; int linecount = 0;

Vect or moduleN ames = new Vect or ();

t r y {


(39)

I/O Example with Reading and

Writing from or to the File (Cont’d)

/ / … cont inued f r om pr evious page.

while (t r ue) {

St r ing line = r eader _d. r eadLine(); if (line == null) {

break; }

St r ingTokenizer t ok = new St r ingTokenizer (line, " "); St r ing module1 = t ok. next Token();

St r ing module2 = t ok. next Token();

moduleN ames. addElement (module1 + "\ t " + module2);

linecount ++; } / / end while


(40)

I/O Example with Reading and

Writing from or to the File (Cont’d)

/ / … cont inued f r om pr evious page.

cat ch (Except ion e) {

e. pr int St ackTrace(); Syst em. exit (1);

}

Buf f er edW r it er wr it er _d; t r y {


(41)

I/O Example with Reading and

Writing from or to the File (Cont’d)

f or (int i = 0; i < moduleN ames. size(); i++) {

St r ing modules = (St ring) moduleN ames. element At (i); wr it er _d. wr it e(modules, 0, modules. lengt h()- 1);

wr it er _d. newLine(); } / / end f or

wr it er _d. close(); } / / end t r y

cat ch (Except ion e) {

e. pr int St ackTrace(); Syst em. exit (1);

}

Syst em. out . pr int ln("N umber of lines: " + linecount ); } / / end main


(42)

Classes

• A class can implement an abstract data type

(ADT).

• Classes protect data with functions (methods) that

safely operate on the data.

• Classes are created with the new keyword.

• The new keyword returns a reference to an object

that represents an instance of the class.

• All instances of classes are allocated in a


(43)

Classes (Cont’d)

• In Java, everything is a class:

– Classes you write

– Classes supplied by the Java specification

– Classes developed by others

– Java extensions

St ring s = new St ring(“This is a t est ”) if (s. st art sW it h(“This”) == t rue)

Syst em. out . print ln(“St art s wit h This”); else


(44)

Classes (Cont’d)

• All classes are derived from a single root class called Obj ect .

• Every class (except Obj ect ) has exactly one immediate super class.

• Only single inheritance is supported.

Class Dot {

f loat x, y; }

class Dot ext ends Obj ect { f loat x, y;


(45)

Casting Classes

• Assume that class B extends class A.

• An instance of B can can be used as an instance of A (implicit cast, widening).

• An instance of A can be used as an instance of B (explicit cast, narrowing).

• Casting between instances of sibling classes in a compile time error.


(46)

Methods

• Methods are like functions.

• Methods are defined inside of a class definition.

• Methods are visible to all other methods defined in the class.

• Methods can be overridden by a subclass.

• Method lookup is done at run-time.


(47)

Methods (Cont’d)

class Arit hmet ic {

int add(int i, int j ){ ret urn i + j ;

}

int sub(int i, int j ){ ret urn i - j ; }

}

Arit hmet ic a = new Arit hmet ic(); Syst em. out . print ln(a. add(1, 2));


(48)

Anatomy of a Method

• Visibility identifier:

public: Accessible anywhere by anyone.

privat e: Accessible only from within the class where they are declared.

pr ot ect ed: Accessible only to subclasses, or other classes in the same package.

Unspecified: Access is public in the class’s package and private elsewhere.

• Return type:

– Must specify a data type of the data that the method returns.

– Use the ret urn keyword.


(49)

Anatomy of a Method (Cont’d)

• Method name

• Argument list:

– List of parameters.

– Each parameter must have a data type.

• Java semantics (IMPORTANT)

Object references are passed by reference, all


(50)

Class (Instance) Variables

• In Java, we can declare variables that are global to the object.

• Define class variables at the top of the class.

• May be defined as public, private or protected.


(51)

Class Variables (Cont’d)

class Add {

int i; / / class variable

int j ; / / class variable / / scope public in t he package, privat e / / elsewhere.

int add(){

ret urn i + j ; }

}


(52)

Class Variables (Cont’d)

• Class variables are defined for each instance of the class. Thus, each object gets its own copy.

• Class variables may be initialized. They are set to 0 or null otherwise. Local variables (inside methods) must be initialized before they can be used.

• May use the st at ic keyword to make a data element common among all class instances.


(53)

Class Variables (Cont’d)

class I ncrement or {

privat e st at ic int i = 0; void incrCount (){

i++; }

int get Count () { ret urn i; }

}

I ncrement or f 1, f 2;

f 1 = new I ncrement or(); f 2 = new I ncrement or(); f 1. incrCount ();

Syst em. out . print ln(f 1. get Count ()); f 2. incrCount ();

Syst em. out . print ln(f 1. get Count ());

What is the output?

What is the output if i is not defined as static?


(54)

this

and

super

• Inside a method, the name this represents the current object.

• When a method refers to its instance variables or methods, this is implied.

• The super variable contains a reference which has the type of the current object’s super class.


(55)

Constants

• In C++, constants are defined using const or

# def ine.

• In Java, it is somewhat more complicated:

– Define a class data element as:

public f inal <st at ic> <dat at ype> <name> = <value>;

– Examples:

public f inal st at ic double PI = 3. 14;

public f inal st at ic int N umSt udent s = 60;


(56)

Arrays

• Arrays in Java are objects.

• Arrays must be allocated.

• Arrays are passed by reference.

• Arrays are 0-based.

int [] i = new int [10];

double [] j = new double[50]; St ring [] s = new St ring[10]; int a[][] = new int [10][3];


(57)

Arrays (Cont’d)

Obj ect

Ar r ay A

f loat [ ] A[ ] int [ ]

/ / You can assign an array t o an Obj ect / / (implicit upcast )

Obj ect o;

int a[ ] = new int [10]; o = a;

/ / You can cast an Obj ect t o an ar r ay / / (explicit downcast )


(58)

Method Overloading

• In Java, we may create methods with the same name.

– Parameter lists must be different. Not enough

to have a different return type.

• Allows for the method to be used based on the called parameters.


(59)

Method Overloading (Cont’d)

class Adder {

int add(int i, int j ) { ret urn i + j ;

}

double add(double i, double j ) { ret urn i + j ;

} }

int i = 4, j = 6; double l = 2. 1, m = 3. 39; Adder a = new Adder();


(60)

Class Constructors

• Each class may have one or more constructors.

• A constructor is a “method” (cannot invoke, does not return anything) that is defined

with the same name as its class.

• A constructor is automatically called when an object is created using new.

• Constructors are valuable for initialization of class variables.


(61)

Class Constructors (Cont’d)

• By default, the super class constructor with no parameters is invoked.

• If a class declares no constructors, the compiler generates the following:

Class MyClass ext ends Ot herClass { MyClass () {

super (); / / aut omat ically gener at ed }


(62)

Class Constructors (Cont’d)

class Bat t er ext ends Player { f loat slugging;

Bat t er (f loat slugging) {

/ / super is called her e t his. slugging = slugging; }

Bat t er () {

t his((f loat ). 450); / / does not call super f ir st }

}

class Pit cher ext ends Bat t er { f loat er a;

Pit cher (f loat er a) {

super ((f loat ). 300); t his. er a = er a;


(63)

Packages

• A package is a loose collection of classes.

• Packages are like libraries.

• Packages may be created using the

package keyword.

• Packages are located by the CLASSPATH environment variable.

• In order to use a package you use the


(64)

Some Common Java Packages

j ava. applet

j ava. j avax

j ava. io

j ava. lang

j ava. net

j ava. ut il

j ava. mat h


(65)

Importing a Package is

Convenient

import j ava. io. * ;

Dat aI nput St ream dis = new Dat aI nput St ream(); or


(66)

The String Class

• Used to create and manipulate strings in Java.

• Better than a null terminated sequence of characters.

• Automatically sized (automatic storage management).


(67)

The String Class (Cont’d)

• Rich set of functions:

– Concatenation

– Lowercase/Uppercase data conversion

– Sub-strings

– Strip leading and trailing characters

– Length

– Data conversion to/from an array of character


(68)

The Vector Class

• The vector class may be used as a dynamic array.

• The vector class can hold any Java object.

import j ava. ut il. Vect or; Vect or v = new Vect or(); v. removeAllElement s();

v. addElement (new St ring(“1”)); v. addElement (new St ring(“2”)); v. addElement (new St ring(“3”)); v. addElement (new St ring(“4”)); f or (int i = 0; i < v. size(); i++)


(69)

Data Conversion Functions

• Java contains a robust set of classes to convert from one data type to another.

• There is a data encapsulation class for each scalar type:

Long for long

I nt eger for int

Float for float

Double for double


(70)

Data Conversion Functions

(Cont’d)

• Typical functionality includes:

– Convert to/from bases

– Convert to/from a string


(71)

Java Events and GUI Programming


(72)

Create the Worker

• We start by creating a worker which will actually do the work

• The example worker is computing all the multiplications of i and j from 1 to 10


(73)

package Hello;

impor t j ava.ut il.Vect or ; impor t j ava.ut il.Enumer at ion;

public class claculat or { pr ivat e int pr og;

public claculat or () { pr og = 0;

}

public void wor k() {

f or (int i=1;i<11;i++) {

f or (int j =1;j <11;j ++) { pr og = i* j ;

not if yList ener s(pr og, f alse); }

} }


(74)

Creating the Main Program

• The main program will simulate the user interface that we will create later

• The main program is responsible to start the worker and receive the results


(75)

package Hello;

public class Hello_main {

public st at ic void main(St r ing ar gs[ ]) {

Hello_main hm = new Hello_main(); Syst em.out .pr int ln("St ar t ");

hm.wor kNoThr ead(); Syst em.out .pr int ln("End"); }

public Hello_main() { }

public void wor kNoThr ead() {

f inal claculat or cc = new claculat or (); Syst em.out .pr int ln("No Thr ead"); cc.wor k();


(76)

Why Isn’t This Enough

• So far we have a main program that starts a worker.

• The main program can receive no

information from the worker until the worker had finished the calculation.

• This situation creates a feeling that the program is stuck and the user is likely to restart it.


(77)

Adding the Event

• The next step is to add an event. The event object

will carry the information from the worker to the main program.

• The event should be customized to fit your needs.

• Our event includes:

– Progress: let the main program know the progress of the worker.

– Finished flag: let the main program know when the worker is done.


(78)

package Hello;

public class I t er at ionEvent { pr ivat e int value_;

pr ivat e boolean f inished_;

public I t er at ionEvent (int value, boolean f inished) { value_ = value;

f inished_ = f inished; }

public int get Value() {

r et ur n value_; }

public boolean isFinished() {

r et ur n f inished_; }


(79)

Adding the Listener

• Now that we have an event object we can build an interface of a listener.

• A listerner will be any object that can receive events.

• The interface should include any function interface that will be implemented in the actual listening object.


(80)

package Hello;

public int er f ace I t er at ionList ener {

public void next I t er at ion(I t er at ionEvent e); }


(81)

The Main Program Revisited

• Now that we have the listener interface we should change the main program to

implement the interface.

• We need to add the implementation of the interface and all the functions that we

declared.


(82)

package Hello;

public class Hello_main

implement s I t er at ionList ener

implement s I t er at ionList ener

{

public st at ic void main(St r ing ar gs[ ]) {

Hello_main hm = new Hello_main(); Syst em.out .pr int ln("St ar t ");

hm.wor kNoThr ead(); Syst em.out .pr int ln("End"); }

public Hello_main() { }

public void wor kNoThr ead() {

f inal claculat or cc = new claculat or (); cc. addList ener (t his);

cc. addList ener (t his);

Syst em.out .pr int ln("No Thr ead"); cc.wor k();

cc. r emoveList ener (t his);

cc. r emoveList ener (t his);

public void next I t erat ion(I t erat ionEvent e)

public void next I t erat ion(I t erat ionEvent e)

{

{

Syst em. out . print ln("From Main:

Syst em. out . print ln("From Main: "+e. get Value());"+e. get Value()); if (e. isFinished()) {

if (e. isFinished()) {

Syst em. out . print ln("Finished");

Syst em. out . print ln("Finished");

}

}

}

}


(83)

The Worker Revisited

• As you might have noticed there are new functions

that we need to add to the worker object: – addListener(IterationListener listener)

• Add a new listener to the worker the listener will receive messages from the worker (you might want more than one).

– removeListener(IterationListener listener)

• Remove a listener from the worker.

– notifyListeners(int value, boolean finished)


(84)

package Hello;

impor t j ava.ut il.Vect or ; impor t j ava.ut il.Enumer at ion;

public class claculat or { pr ivat e int pr og;

pr ivat e Vect or list ener s_ = new Vect or ();

public claculat or () { pr og = 0;

}

public void wor k() {

f or (int i=1;i<11;i++) {

f or (int j =1;j <11;j ++) { pr og = i* j ;

not if yList ener s(prog, f alse);

not if yList ener s(prog, f alse);

} }

not if yList ener s(prog, t r ue);

not if yList ener s(prog, t r ue);

public void addList ener (I t erat ionList ener list ener )

public void addList ener (I t erat ionList ener list ener )

{

{

list ener s_. addElement (list ener );

list ener s_. addElement (list ener );

}

}

public void r emoveList ener (I t er at ionList ener list ener )

public void r emoveList ener (I t er at ionList ener list ener )

{

{

list ener s_. r emoveElement (list ener );

list ener s_. r emoveElement (list ener );

}

}

privat e void not if yList ener s(int value, boolean f inished)

privat e void not if yList ener s(int value, boolean f inished)

{

{

I t erat ionEvent e = new I t erat ionEvent (value, f inished);

I t erat ionEvent e = new I t erat ionEvent (value, f inished);

f or (Enumer at ion list ener s = list ener s_. element s();

f or (Enumer at ion list ener s = list ener s_. element s();

list ener s. hasMor eElement s(); )

list ener s. hasMor eElement s(); )

{

{

I t er at ionList ener l = (I t er at ionList ener )

I t er at ionList ener l = (I t er at ionList ener ) list ener s. next Element ();list ener s. next Element (); l. next I t er at ion(e);

l. next I t er at ion(e);

}

}

}

}


(85)

I Am Confused...

• Lets see what are the new things mean:

addList ener (I t er at ionList ener list ener ).addList ener (I t er at ionList ener list ener ).

• This function adds a new vector element to the listeners vector (you may have as many listeners as you wish).

r emover emoveList ener (I t er at ionList ener list ener).List ener (I t er at ionList ener list ener).

• This function removes a listener from the listeners vector this will free the listener object once you don’t need it anymore.

not if yList ener s(int value, boolean f inished).not if yList ener s(int value, boolean f inished).

• This function is the function that sends the information to the main program.

• The f or loop runs through all the listener elements in the listeners vector and uses the next I t er at ion(e)next I t er at ion(e) function that is implemented in the listener it self.

• When the worker call the not if yList ener snot if yList ener sfunction the main program runs the next I t er at ion(e)next I t er at ion(e) function and updates it self.


(86)

How About Another Listener

• As was said before we can have more than one listener, lets see how we can do that.

• Remember that the listener needs to

implement the interface and the functions of that interface.


(87)

package Hello;

impor t j ava.ut il.Calendar ; impor t j ava.io.* ;

public class Pr int er

implement s I t er at ionList ener {

public void next I t er at ion(I t er at ionEvent e) { Calendar Now = Calendar .get I nst ance(); t r y {

FileW r it er f os = new FileW r it er ("C:\ \ Ron Pr oj ect s\ \ EvensI nSwt ing\ \ pr int er .log",t r ue); f os.wr it e("Fr om Pr int er - " + Now.get Time() + " Value: "+ e.get Value()+"\ n");

/ / Syst em.out .pr int ln("Fr om Pr int er - " + Now.get Time() + " Value: "+ e.get Value()); if (e.isFinished()) {

f os.wr it e("Fr om Pr int er - "+Now.get Time()+" Finished\ n"); / / Syst em.out .pr int ln("Finished");

}

f os.close();

} cat ch (j ava.io.I OExcept ion ex) { Syst em.out .pr int ln("Opps: " + ex); }


(88)

The Printer Object

• The printer object is just another listener that will update a log file for the main

program.

• Notice that this listener should be added

from the main program but is completely in-depended from the main program


(89)

Threading the Worker

• If you want to thread the worker without changing it the next code segment that is part of the main program shows how to thread the worker from within the main program.

• We add the function workThread() workThread() to the


(90)

public void wor kThr ead() {

f inal claculat or cc = new claculat or (); cc.addList ener (t his);

cc.addList ener (new Pr int er ()); Syst em.out .pr int ln("W it h Thr ead"); Thr ead t = new Thr ead() {

public void r un() { cc.wor k();

} };

t .st ar t (); t r y {

t .j oin(); }

cat ch (Except ion e) { }

cc.r emoveList ener (t his); }


(91)

Real Threads

• If you want more information on how to build a real threaded program visit this URL:


(92)

The Output From the Main

Program


(93)

The Content of the Log File

From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 1 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 2 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 3 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 4 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 5 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 6 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 7 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 8 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 9 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 10 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 11 From Printer - Tue Aug 22 13:18:17 EDT 2000 Value: 12...


(94)

• Lets see how we can add a nice graphical user interface to out little example.

• The UI will need to display:

– Start button:

– Progress bar:

– Current value:

– Status bar:


(95)

Creating Main Frame

• The Main Frame is extending Swing Jframe.

• We will implement IterationListener again to get the information from the worker.


(96)

Main Frame Cont.

• The following code segments show how to declare the frame:

– Create the content pane

– Create the layout

– Create different fields (buttons, text,


(97)

package Hello; impor t j ava.awt .* ;

impor t j ava.awt .event .* ; impor t j avax.swing.* ;

impor t j avax.swing.event .* ; impor t j ava.io.File;

impor t j avax.swing.UI Manager ;

public class Hello_Fr ame1

ext ends J Fr ame implement s I t er at ionList ener {

J Panel cont ent Pane;

J Label st at usBar = new J Label(); Bor der Layout bor der Layout 1 = new Bor der Layout ();

J Panel j Panel1 = new J Panel();

Gr idBagLayout gr idBagLayout 1 = new Gr idBagLayout ();

J Label j Label1 = new J Label();

J But t on j But t onRun = new J But t on(); J Label j LabelCur r ent Value = new J Label(); J Pr ogr essBar j Pr ogr essBar = new

J Pr ogr essBar (0,100);

public Hello_Fr ame1() {

cont ent Pane = (J Panel) t his.get Cont ent Pane(); cont ent Pane.set Layout (bor der Layout 1);

t his.set Size(new Dimension(400, 300)); t his.set Tit le("Hello GUI ");

st at usBar .set Opaque(t r ue); st at usBar .set Text ("Ready");

j Panel1.set Layout (gr idBagLayout 1);

j Label1.set Text ("Click her e t o st ar t t he pr ocess:"); j LabelCur r ent Value.set Text ("Not Running");

j But t onRun.set Text ("Run"); j Pr ogr essBar .set Value(0);

j LabelPr ogr ess.set Text ((St r ing)

(new I nt eger (j Pr ogr essBar .get Value())).t oSt r ing()+"%"); j Label2.set Text ("Cur r ent Value:");


(98)

cont ent Pane.add(st at usBar , Bor der Layout .SOUTH); cont ent Pane.add(j Panel1, Bor der Layout .CENTER);

j Panel1.add(j Label1, new Gr idBagConst r aint s(0, 0, 1, 1, 0.0, 0.0

,Gr idBagConst r aint s.W EST, Gr idBagConst r aint s.NONE, new I nset s(5, 5, 5, 5), 0, 0)); j Panel1.add(j But t onRun, new Gr idBagConst r aint s(1, 0, 1, 1, 0.0, 0.0

,Gr idBagConst r aint s.W EST, Gr idBagConst r aint s.NONE, new I nset s(5, 5, 5, 5), 0, 0)); j Panel1.add(j Pr ogr essBar , new Gr idBagConst r aint s(0, 1, 1, 1, 0.0, 0.0

,Gr idBagConst r aint s.W EST, Gr idBagConst r aint s.NONE, new I nset s(5, 5, 5, 5), 0, 0)); j Panel1.add(j LabelPr ogr ess, new Gr idBagConst r aint s(1, 1, 1, 1, 0.0, 0.0

,Gr idBagConst r aint s.W EST, Gr idBagConst r aint s.NONE, new I nset s(5, 5, 5, 5), 0, 0)); j Panel1.add(j Label2, new Gr idBagConst r aint s(0, 2, 1, 1, 0.0, 0.0

,Gr idBagConst r aint s.W EST, Gr idBagConst r aint s.NONE, new I nset s(5, 5, 5, 5), 0, 0)); j Panel1.add(j LabelCur r ent Value, new Gr idBagConst r aint s(1, 2, 1, 1, 0.0, 0.0

,Gr idBagConst r aint s.W EST, Gr idBagConst r aint s.NONE, new I nset s(5, 5, 5, 5), 0, 0)); }


(99)

The Main Frame With the

Controls


(100)

Button Functionality

• We have only one button and we need to add a listener to it.

• We can add an addActionListener and implement it later.

• The following code segments show how to add the listener, create the class and


(1)

Button Functionality Cont.

After the declaration of the listener we

implement the actionPerformed function in

a new function:

jButtonRun_actionPerformed.

In this function we will run the calculator in

a similar way to the non-GUI way.

We add the Frame as the listener and

implement how it will listen later.


(2)

j But t onRun.addAct ionList ener (new j ava.awt .event .Act ionList ener () {

public void act ionPer f or med(Act ionEvent e) {

j But t onRun_act ionPer f or med(e); }

};

void j But t onRun_act ionPer f or med(Act ionEvent e) {

change_st at us(Color .r ed, "W or king Please wait ..."); f inal claculat or cc = new claculat or ();

f inal I t er at ionList ener list ener = t his; / / cc.addList ener (new Pr int er ()); Thr ead t = new Thr ead() {

public void r un() {

cc.addList ener (list ener ); cc.wor k();

cc.r emoveList ener (list ener ); }


(3)

GUI nextIteration

Implementation

The new function will need to update the

GUI with the status of the worker:

Change the status bar to a working mode.

Update:

Current value field.

Status Bar.

Complete percentage.

When done open the ‘Done’ dialog box and

reset everything to the starting state.


(4)

public void next I t er at ion(I t er at ionEvent e) {

/ / Syst em.out .pr int ln(e.get Pr ogr ess()); j Pr ogr essBar .set Value(e.get Pr ogr ess());

j LabelPr ogr ess.set Text ((St r ing) (new I nt eger (j Pr ogr essBar .get Value())).t oSt r ing()+"%"); j LabelCur r ent Value.set Text ((St r ing) (new I nt eger (e.get Value()).t oSt r ing() ));

if (e.isFinished()) {

change_st at us(Color .get Color ("204,204,204"), "Ready"); / / St ar t t he f inished dialogBox

Hello_Fr ameAbout dlg = new Hello_Fr ameAbout (t his); Dimension dlgSize = dlg.get Pr ef er r edSize();

Dimension f r mSize = get Size(); Point loc = get Locat ion();

dlg.set Locat ion((f r mSize.widt h - dlgSize.widt h) / 2 + loc.x, (f r mSize.height - dlgSize.height ) / 2 + loc.y); dlg.set Modal(t r ue);

dlg.show();

j Pr ogr essBar .set Value(0); j LabelPr ogr ess.set Text ("0%");


(5)

Summary

I hope you gained some knowledge of how to

create and manage Swing applications and events.

Source code the complete example as well as the

compiled version is available to download.

Usage:

Java –classpath Hello.jar Hello.Hello_main filename


(6)

References

[Mitchell99] B. S. Mitchell class lecture

notes.

[Sun96] The Java Language Tutorial, Sun

Microsystems.

[JDK99] The Online Java Tutorial