Introduction to Computing Using Java Exception Handling Array

  • Slides: 76
Download presentation
Introduction to Computing Using Java Exception Handling, Array & GUI Copyright by Michael P.

Introduction to Computing Using Java Exception Handling, Array & GUI Copyright by Michael P. F. Fung 1

Exception (例外/情況/鑊) • When running a program, there may be unexpected conditions or errors.

Exception (例外/情況/鑊) • When running a program, there may be unexpected conditions or errors. E. g. – Network outage causing read error. – I/O Error (disk damage, disk full, etc. ) • It’s an art to handle the exceptions gracefully and correctly. X – We won’t expect a blue screen during the course of running our programs! Copyright by Michael P. F. Fung 2

Exceptionally Ugly Copyright by Michael P. F. Fung 3

Exceptionally Ugly Copyright by Michael P. F. Fung 3

How to Deal With Exceptions • Each exception is given a meaningful name, indicating

How to Deal With Exceptions • Each exception is given a meaningful name, indicating the nature of it. • We may define our own exceptions with our given names. • Java has already defined some commonly used ones. – IOException, Arithmetic. Exception, EOFException, etc. • In any method, we may: – Raise exceptions (throw) – Detect exceptions (try) and Handle exceptions (catch) – Ignore exceptions (declare throws clause and propagate) • Ignore means the method would suicide. • The suicided method would become a killer (exception propagation). Copyright by Michael P. F. Fung 4

IOException Objects • Used when something gone wrong during general Input/Output operations. • We

IOException Objects • Used when something gone wrong during general Input/Output operations. • We may create (new) an IOException object from the class java. io. IOException. import java. io. *; . . . new IOException(); Copyright by Michael P. F. Fung 5

Throwing IOException • If we found/felt something wrong with I/O, we may create and

Throwing IOException • If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4 -figure table from file if (something_wrong_during_input) throw new IOException(); else. . . return answer; } Copyright by Michael P. F. Fung … void main(…) { double value = tan(30); } Normal return 6

Throwing IOException • If we found/felt something wrong with I/O, we may create and

Throwing IOException • If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4 -figure table from file if (something_wrong_during_input) throw new IOException(); else. . . return answer; } Copyright by Michael P. F. Fung … void main(…) { double value = tan(30); } Abnormal return “throwing exception” 7

Throwing IOException • If we found/felt something wrong with I/O, we may create and

Throwing IOException • If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4 -figure table from file if (something_wrong_during_input) throw new IOException(); else. . . return answer; } … void main(…) { double value = tan(30); } Rest skipped, method terminated Copyright by Michael P. F. Fung 8

Still Something Wrong: Exception Declaration • If we compile the above “program”, we will

Still Something Wrong: Exception Declaration • If we compile the above “program”, we will get a compilation error. • We have to tell message senders: be ready to receive (possible) IOException’s: declaration. double tan(double angle) throws IOException { // read a 4 -figure table from file if (something_wrong_during_input) throw new IOException(); else. . . return answer; } Copyright by Michael P. F. Fung 9

Detecting Exceptions • In the previous example, main() will be puzzled on receiving the

Detecting Exceptions • In the previous example, main() will be puzzled on receiving the IOException object from tan(). • What should we do in the message sender? • We have to define a try block in the message sender to detect exceptions. … void main(…) { double value = tan(30); } Copyright by Michael P. F. Fung 10

Try Block • From the signature of tan(), we know that sending this message

Try Block • From the signature of tan(), we know that sending this message is risky. double tan(double angle) throws IOException { … } … void main(…) { double value; try { value = tan(30); value = value * 3. 14159; } } Copyright by Michael P. F. Fung 11

Try Block • In case of receiving any exceptions from any statements in the

Try Block • In case of receiving any exceptions from any statements in the try block, the rest (subsequent) statements in the try block will be skipped. double tan(double angle) throws IOException { … throw new IOException(); } … void main(…) { double value; try { value = tan(30); value = value * 3. 14159; // wow, skipped } } Copyright by Michael P. F. Fung 12

Limited Liability • Skipping the remaining statements in the try block means saving the

Limited Liability • Skipping the remaining statements in the try block means saving the method from dying! Something is missing here… See next slide. . . … void main(…) { double value; try { value = tan(30); value = value * 3. 14159; // wow, skipped } double result = value + 19 * 97 - 2002; } • It avoids skipping the rest statements in the whole method body! i. e. rescuing the method. Copyright by Michael P. F. Fung 13

Twins: Detection and Handling • In fact, try and catch are twins. • Try

Twins: Detection and Handling • In fact, try and catch are twins. • Try is responsible for detection. • Catch is responsible for identification and handling. Copyright by Michael P. F. Fung 14

Handling Exceptions double tan(double angle) throws IOException { if (read_4_figure_table_error) throw new IOException(); …

Handling Exceptions double tan(double angle) throws IOException { if (read_4_figure_table_error) throw new IOException(); … } … void main(…) { double value; try { value = tan(30); value = value * 3. 14159; // wow, skipped … } catch (IOException io_exception_object_ref) { System. out. println(“Input Output Exception received!”); value = 3. 14159; } // the program continues normally hereafter } Copyright by Michael P. F. Fung 15

Handling Exceptions • We catch certain type of exception by: catch (Exception. Type an_object_reference)

Handling Exceptions • We catch certain type of exception by: catch (Exception. Type an_object_reference) { statements to remedy the condition; } // resume normal execution hereafter • an_object_reference lets us access the fields/methods of the exception object. • Thus further information may be passed from the exception thrower to the exception handler through the exception object. Copyright by Michael P. F. Fung 16

Catching Several Kinds of Possible Exceptions double tan(double angle) throws IOException, Arithmetic. Exception {

Catching Several Kinds of Possible Exceptions double tan(double angle) throws IOException, Arithmetic. Exception { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new Arithmetic. Exception(); } … void main(…) { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3. 14159; // wow, skipped } catch (IOException io_exception_object_ref) { System. out. println(“Input Output Exception received!”); value = 3. 14159; } catch (Arithmetic. Exception arithmetic_exception_object_ref ) { System. out. println(“Arithmetic Exception received!”); value = 0. 0; } // the program continues normally hereafter } Copyright by Michael P. F. Fung 17

Exception Propagation • Unless encountering a try-catch block which handles the received exception, the

Exception Propagation • Unless encountering a try-catch block which handles the received exception, the exception will cause termination of the current method. • In such case, the method re-throws (propagates) the same exception object to its message sender. • The involved method should therefore declare that it may throw that exception in its method signature. Copyright by Michael P. F. Fung 18

Exception Propagation double tan(double angle) throws IOException, Arithmetic. Exception { if (read_4_figure_table_error) throw new

Exception Propagation double tan(double angle) throws IOException, Arithmetic. Exception { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new Arithmetic. Exception(); } … void main(…) throws Arithmetic. Exception { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3. 14159; // wow, skipped } catch (IOException io_exception_object_ref) { System. out. println(“Input Output Exception received!”); System. out. println(“We have handled it gracefully!”); value = 3. 14159; } // Arithmetic. Exception is not caught // this method terminates and propagates the arithmetic exception object // on receiving Arithmetic. Exception } Copyright by Michael P. F. Fung 19

Top-Level Boss • The Java Virtual Machine is the first message sender which sends

Top-Level Boss • The Java Virtual Machine is the first message sender which sends a message to main(). • It is thus the ultimate receiver of any un-handled exceptions. • The exception propagation stops either on: – Reaching a try-catch block which handles the exception. – Or reaching the JVM and causing program termination. Copyright by Michael P. F. Fung 20

Array • Popular and important data structure – use an index to access variables

Array • Popular and important data structure – use an index to access variables of the same name (identifier) and type: i[0] = 5; i[654] = -378; • How to do that? int[] i = new int[1000]; – OR( C++ style ) int i[] = new int[1000]; Copyright by Michael P. F. Fung 21

Declaration and Array Creation int[] i = new int[1000]; is equivalent to int[] i;

Declaration and Array Creation int[] i = new int[1000]; is equivalent to int[] i; i = new int[1000]; Copyright by Michael P. F. Fung // i is nothing yet // i keeps something 22

Another Form of Array Creation • By enumerating its initial values: char[] vowels =

Another Form of Array Creation • By enumerating its initial values: char[] vowels = {'a', 'e', 'i', 'o', 'u'}; • Then vowels is an array of 5 char variables with vowels[0] vowels[1] vowels[2] vowels[3] vowels[4] 'a' 'e' 'i' 'o' 'u' There are 5 char variables! • Array index must be an integer: [0 to length – 1]. Copyright by Michael P. F. Fung 23

Syntax of Creating Arrays type[] array_name = new type[length]; type[] array_name = {value 1,

Syntax of Creating Arrays type[] array_name = new type[length]; type[] array_name = {value 1, value 2, . . . }; e. g. double[] String char[] GPA = new double[50]; country. Code = new String[175]; address[] = new String[30]; vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; • type may be primitive type, class type or even an other array type. Copyright by Michael P. F. Fung 24

Properties of Array • A bounded (fixed length) and indexed collection of elements of

Properties of Array • A bounded (fixed length) and indexed collection of elements of the same type. • Array length is fixed at the time of creation. • Element access is done using an index [ ]. – vowels[0] to vowels[vowels. length – 1] – vowels[-8] Array. Index. Out. Of. Bounds. Exception • To get the length (size) of an array: – vowels. length – NOT vowel. length() [confused with String] Copyright by Michael P. F. Fung 25

Example: The Parameter in main() class Test. Args { public static void main(String[] args)

Example: The Parameter in main() class Test. Args { public static void main(String[] args) { System. out. println("There are " + args. length + " arguments: "); int i; for (i = 0; i < args. length; i++) System. out. println( args[i] ); } } C: Let. See> There are 0 C: Let. See> There are 2 Apple Orange java Test. Args arguments: java Test. Args Apple Orange arguments: Copyright by Michael P. F. Fung 26

Example: The Parameter in main() • A Java application program can receive some parameters

Example: The Parameter in main() • A Java application program can receive some parameters at start-up. • These start-up parameters are called command-line arguments. • The main() method is the receiver of such arguments. • Such arguments are stored in a String array created by the JVM. • JVM sends a message to main() with such an array. Copyright by Michael P. F. Fung 27

Array of Object References int[] i; // a null integer array reference i =

Array of Object References int[] i; // a null integer array reference i = new int[100]; // create a new integer array i[5] = 87; // let i refer to the array // initially, i[0] = … = i[99] = 0 Octopus[] deck; // a null Octopus array reference deck = new Octopus[10]; // initially, deck[0] = … = null deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); • Creating a new array Creating members Copyright by Michael P. F. Fung 28

Array Itself is Also a Reference deck[ ] (reference) ? Octopus[] deck; deck =

Array Itself is Also a Reference deck[ ] (reference) ? Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); Copyright by Michael P. F. Fung 29

Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0]

Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright by Michael P. F. Fung ? ? ? Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 30

Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0]

Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright by Michael P. F. Fung ? ? Octopus (object) Octopus (class) Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 31

Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0]

Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright by Michael P. F. Fung ? Octopus (object) Octopus (class) Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 32

Array Itself is Also a Reference Octopus (object) deck[ ] (reference) deck[2] (reference) deck[1]

Array Itself is Also a Reference Octopus (object) deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Class type array Copyright by Michael P. F. Fung Octopus (class) Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 33

Array Itself is Also a Reference i[ ] (reference) Primitive type array Class type

Array Itself is Also a Reference i[ ] (reference) Primitive type array Class type array Copyright by Michael P. F. Fung i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 int[] i; i = new int[3]; i[0] = 7; i[1] = i[0]; i[2] = 9; 34

Assignment of the Whole Array i[ ] (reference) j[ ] (reference) Copyright by Michael

Assignment of the Whole Array i[ ] (reference) j[ ] (reference) Copyright by Michael P. F. Fung They refer to the same array! i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 int[] i = new int[3]; int[] j; j = i; // object reference copying j[2] = 9; // i[2] = 9 i[1] = 7; // j[2] = 7 j[0] = 7; // i[0] = 7 35

Assignment of the Whole Array i[ ] (reference) j[4] j[3] j[2] (int) j[1] (int)

Assignment of the Whole Array i[ ] (reference) j[4] j[3] j[2] (int) j[1] (int) j[0] 0(int) 00 Copyright by Michael P. F. Fung OR, Create another one! i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 int[] i = new int[3]; int[] j; j = new int[5]; 36

Assignment of the Whole Array i[ ] (reference) j[4] j[3] j[2] (int) j[1] (int)

Assignment of the Whole Array i[ ] (reference) j[4] j[3] j[2] (int) j[1] (int) j[0] 0(int) 00 Copyright by Michael P. F. Fung Remember to Keep It Well! i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 int[] i = new int[3]; int[] j; j = new int[5]; j = i; 37

New Concept: Primitive Type Array Argument Passing class Student { public static void study.

New Concept: Primitive Type Array Argument Passing class Student { public static void study. Hard(double[] new. GPAs) { new. GPAs[0] = 4. 0; new. GPAs[1] = 4. 0; } Start here public static void main(String[] args) { double[] GPAs = new double[2]; GPAs[0] = 1. 0; GPAs[1] = 1. 5; Student. study. Hard(GPAs); System. out. println(GPAs[0]); System. out. println(GPAs[1]); } new. GPAs (Reference) GPAs[1] 1. 5 4. 0 GPAs[0] 1. 0 4. 0 GPAs (Reference) } Copy array reference to formal parameter when sending message. Change to. Michael the formal Copyright by P. F. Fung parameter DOES NOT affect actual parameter! 38

New Concept: Object Type Array Argument Passing Start here class CUHK { public static

New Concept: Object Type Array Argument Passing Start here class CUHK { public static void fire(Employee[] victims) { for (int i = 0; i < victims. length; i++) victims[i]. salary = 0; } public static void main(String[] args) { Employee[] TAs = new Employee[3]; TAs[0] = new Employee(1000); TAs[1] = new Employee(2000); TAs[2] = new Employee(5000); CUHK. fire(TAs); } } TAs (reference) class Employee { public int salary; public Employee(int initial. Salary) { salary = initial. Salary; } } Copyright by Michael P. F. Fung victims (reference) Employee (object) salary 1000 TAs[0] (reference) TAs[1] (reference) Employee (object) salary 2000 Employee (object) salary 5000 TAs[2] (reference) 39

Table (2 -Level Array) What’s the type? double // There are 176 students, 8

Table (2 -Level Array) What’s the type? double // There are 176 students, 8 assignments // record their marks in double[][] mark = new double[176][8]; mark[6][0] = 99. 34; // mark: 7 th student, Asg 1 mark[175][6] = 89. 12; // mark: last student, Asg 7 double[] single. Student; single. Student = mark[175]; // refer to the single. Student[6] = 45. 67; // marks of the last one System. out. println(mark[175][6]); // would print 45. 67 • Elements of an array could be arrays. • Array reference of array references. Copyright by Michael P. F. Fung 40

Table Illustrated mark[ ][ ] (reference) Array of double Copyright by Michael P. F.

Table Illustrated mark[ ][ ] (reference) Array of double Copyright by Michael P. F. Fung mark[2] mark[1] mark[0] (reference) mark[2][3] (double) 9. 45 mark[1][3] (double) 8. 48 mark[0][3] (double) 9. 11 mark[2][2] (double) 2. 49 mark[1][2] (double) 3. 40 mark[0][2] (double) 1. 42 mark[2][1] (double) 3. 43 mark[1][1] (double) 6. 13 mark[0][1] (double) 5. 43 mark[2][0] (double) 1. 75 mark[1][0] (double) 1. 15 mark[0][0] (double) 0. 35 41

Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9

Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 int[] i = {7, 7, 9}; int[] j; j = new int[i. length]; for (int count = 0; count < i. length; count++) j[count] = i[count]; Copyright by Michael P. F. Fung 42

Duplicating an int Array i[ ] (reference) j[ ] (reference) ? Copyright by Michael

Duplicating an int Array i[ ] (reference) j[ ] (reference) ? Copyright by Michael P. F. Fung Copy the elements one-by-one i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 int[] i = {7, 7, 9}; int[] j; j = new int[i. length]; for (int count = 0; count < i. length; count++) j[count] = i[count]; 43

Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9

Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 j[ ] (reference) j[2] (int) 0 Copyright by Michael P. F. Fung j[1] (int) 0 j[0] (int) 0 i[1] (int) 7 i[0] (int) 7 int[] i = {7, 7, 9}; int[] j; j = new int[i. length]; for (int count = 0; count < i. length; count++) j[count] = i[count]; 44

Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9

Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 j[ ] (reference) j[2] (int) 9 Copyright by Michael P. F. Fung j[1] (int) 7 j[0] (int) 7 i[1] (int) 7 i[0] (int) 7 int[] i = {7, 7, 9}; int[] j; j = new int[i. length]; for (int count = 0; count < i. length; count++) j[count] = i[count]; 45

Duplicating an Object Array deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright

Duplicating an Object Array deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright by Michael P. F. Fung Octopus (object) Octopus (class) Octopus[] deck; . . . Octopus[] new. Deck; new. Deck = new Octopus[deck. length]; for (int count = 0; count < deck. length; count++) new. Deck[count] = deck[count]; 46

Duplicating an Object Array new. Deck[ ] (reference) ? deck[ ] (reference) deck[2] (reference)

Duplicating an Object Array new. Deck[ ] (reference) ? deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright by Michael P. F. Fung Octopus (object) Octopus (class) Octopus[] deck; . . . Octopus[] new. Deck; new. Deck = new Octopus[deck. length]; for (int count = 0; count < deck. length; count++) new. Deck[count] = deck[count]; 47

Duplicating an Object Array new. Deck[ ] (reference) new. Deck[2] (reference) new. Deck[1] (reference)

Duplicating an Object Array new. Deck[ ] (reference) new. Deck[2] (reference) new. Deck[1] (reference) new. Deck[0] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright by Michael P. F. Fung Octopus (object) Octopus (class) Octopus[] deck; . . . Octopus[] new. Deck; new. Deck = new Octopus[deck. length]; for (int count = 0; count < deck. length; count++) new. Deck[count] = deck[count]; 48

Duplicating an Object Array new. Deck[ ] (reference) new. Deck[2] (reference) new. Deck[1] (reference)

Duplicating an Object Array new. Deck[ ] (reference) new. Deck[2] (reference) new. Deck[1] (reference) new. Deck[0] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Copyright by Michael P. F. Fung Octopus (object) Octopus (class) Only the object references are copied! Octopus[] deck; . . . Octopus[] new. Deck; new. Deck = new Octopus[deck. length]; for (int count = 0; count < deck. length; count++) new. Deck[count] = deck[count]; 49

7 -Minute Break Copyright by Michael P. F. Fung 50

7 -Minute Break Copyright by Michael P. F. Fung 50

Graphics User Interface(GUI) • Graphical User Interface • Basic Elements • Event Driven Model

Graphics User Interface(GUI) • Graphical User Interface • Basic Elements • Event Driven Model • Trigger and Callback Copyright by Michael P. F. Fung 51

Command-line User Interface Copyright by Michael P. F. Fung 52

Command-line User Interface Copyright by Michael P. F. Fung 52

Graphical User Interface Copyright by Michael P. F. Fung 53

Graphical User Interface Copyright by Michael P. F. Fung 53

GUI – Computer Display • Use of graphical representations – Windows – Icons –

GUI – Computer Display • Use of graphical representations – Windows – Icons – Buttons –… • To convey the underlying concepts – An icon represents a file – A button represents certain function Copyright by Michael P. F. Fung 54

GUI – User Input • Use of various interactive input devices – – Keyboard

GUI – User Input • Use of various interactive input devices – – Keyboard Mouse Touch screen … • To gather command control from user – A mouse click opens a file – A mouse drag moves a window – Pressing means “OK” Copyright by Michael P. F. Fung 55

GUI and OOP • • A window is an object. A button is an

GUI and OOP • • A window is an object. A button is an object. We create windows and buttons from classes. Such objects – – store state of the component (field/property); perform certain function (method); generates events (event objects); respond to user actions (callback method); Copyright by Michael P. F. Fung 56

1) Store State • Basic properties – Colour – Size – Visibility • Dynamic

1) Store State • Basic properties – Colour – Size – Visibility • Dynamic states – On/off state of a button – Value of a text field Copyright by Michael P. F. Fung 57

2) Perform Action Paint the window Draw circles Display text Copyright by Michael P.

2) Perform Action Paint the window Draw circles Display text Copyright by Michael P. F. Fung 58

3) Generate Event Detect if you dragged the scrollbar Detect if you clicked a

3) Generate Event Detect if you dragged the scrollbar Detect if you clicked a button Detect if you dragged the mouse pointer Copyright by Michael P. F. Fung 59

4) Handle Event • On clicking the buttons, moving the mouse, dragging the mouse,

4) Handle Event • On clicking the buttons, moving the mouse, dragging the mouse, … over a component, events are generated. • On receiving an event, the corresponding callback method of a listener is invoked. • The method may update the screen, update the state, perform some function, etc. Copyright by Michael P. F. Fung 60

How to Do it Using Java? • One of the provided packages java. awt

How to Do it Using Java? • One of the provided packages java. awt (Abstract Windowing Toolkit) is readily used. • There are plenty of component classes well-defined in the package. – Frame: basically a window – Button: a push button with a label – Text. Field… Copyright by Michael P. F. Fung 61

Simple Example import java. awt. *; /* This is not the usual way we

Simple Example import java. awt. *; /* This is not the usual way we call up GUI * Normally, we should subclass (extends) some * GUI components in order to modify the behaviour */ class Simple. GUI { public static void main(String[] args) { Frame my. Window = new Frame(); my. Window. set. Title("Simple GUI"); my. Window. set. Size(200, 100); my. Window. set. Visible(true); } } Copyright by Michael P. F. Fung 62

Components List - Classes Copyright by Michael P. F. Fung 63

Components List - Classes Copyright by Michael P. F. Fung 63

How to Use the Components? • • Read the API Manual and Books! Check

How to Use the Components? • • Read the API Manual and Books! Check for the components you need Create (new) the components Set their properties – Basic properties and initial state – Relationship between the components – Action to be performed on event happening Copyright by Michael P. F. Fung 64

Component - Basic Properties • Colour : set. Background(Color) set. Foreground(Color) • Size :

Component - Basic Properties • Colour : set. Background(Color) set. Foreground(Color) • Size : set. Size(int, int) • Position : set. Location(int, int) • State : set. Enabled(boolean) • Font : set. Font(Font) • Visibility : set. Visible(boolean) • … Copyright by Michael P. F. Fung 65

Component - Relationship • Sibling/sub-ordinary relationship Button 1 and Button 2 are contained/embedded in

Component - Relationship • Sibling/sub-ordinary relationship Button 1 and Button 2 are contained/embedded in the Frame window. add(button 1); Button 1 is on the left of Button 2 on the same row • Relative position between the components Copyright by Michael P. F. Fung 66

Component - Event Generation • Events are automatically generated during interaction with the user.

Component - Event Generation • Events are automatically generated during interaction with the user. • Events are normally happened in conjunction with certain component(s). • If the involved component(s) do not listen to (pay attention to) that event, normally nothing would happen. Copyright by Michael P. F. Fung 67

Component - Event Listening • To listen to an event, we need a listener:

Component - Event Listening • To listen to an event, we need a listener: Frame my. Window = new Frame(); /* Adapter is a kind of Listener */ Window. Adapter adapter = new Window. Adapter(); my. Window. add. Window. Listener(adapter); • add*Listener() are methods of components. • We register a listener to listen to certain kind of events, say Mouse. Event. – e. g. Mouse. Listener may be Mouse. Adapter objects. Copyright by Michael P. F. Fung 68

Event Handling Button 1 User action Generates Mouse. Event Mouse. Listener Mouse. Adapter Event

Event Handling Button 1 User action Generates Mouse. Event Mouse. Listener Mouse. Adapter Event Handler may: - Update the appearance of the button - Modify the state of the button - Perform programmer-defined action such as “Say Hello” Copyright by Michael P. F. Fung mouse. Clicked mouse. Entered Event mouse. Pressed Dispatching … 69

Listener Example import java. awt. *; import java. awt. event. *; class Listen. GUI

Listener Example import java. awt. *; import java. awt. event. *; class Listen. GUI { public static void main(String[] args) { Frame my. Window = new Frame(); my. Window. set. Title("Simple GUI"); my. Window. set. Size(200, 100); my. Window. set. Visible(true ); my. Window. add. Window. Listener(new My. Window. Adapter()); } } File Listen. GUI. java class My. Window. Adapter extends Window. Adapter { public void window. Closing(Window. Event e) { System. out. println(“Terminating the program!”); System. exit(1); // a message to ask the System to exit //. . . OR you may open other windows!!! } } Copyright by Michael P. F. Fung 70

Handler (Callback) Method • An adapter in fact normally listens to a set of

Handler (Callback) Method • An adapter in fact normally listens to a set of related events. • For each kind of event, a corresponding handler method is defined. • On receiving a Mouse. Event which indicates mouse button pressed, the mouse. Pressed() method of the Mouse. Adapter object will be invoked. Copyright by Michael P. F. Fung 71

Customizing the Handling • Without customizing (overriding) the default handler methods provided in the

Customizing the Handling • Without customizing (overriding) the default handler methods provided in the adapter, nothing would happen. • That’s why we extends the Window. Adapter, Mouse. Adapter… classes. • By re-defining (overriding) their methods, we can achieve desired behaviour in event handling. Copyright by Michael P. F. Fung 72

Examples • • • Normal. Mouse. Adapter Normal. Window. Adapter Normal. GUI Listen. GUI

Examples • • • Normal. Mouse. Adapter Normal. Window. Adapter Normal. GUI Listen. GUI 2 Copyright by Michael P. F. Fung 73

What Kinds of Events? • Examples: – Window. Event needs Window. Listener. Window. Adapter

What Kinds of Events? • Examples: – Window. Event needs Window. Listener. Window. Adapter is a kind of Window. Listener. – Mouse. Event needs Mouse. Listener. Mouse. Adapter is a kind of Mouse. Listener. • The events themselves are generated by some components under user interaction. Copyright by Michael P. F. Fung 74

After-Life of main() • When and how does a GUI program end? • main()

After-Life of main() • When and how does a GUI program end? • main() is the first method to be invoked. • Normally, after main() finishes, the program ends. • But this is not the case for GUI programs. . . • Why? The underlying event dispatching loop of the system takes over the control. Copyright by Michael P. F. Fung 75

Advanced Topics • Using Swing/ AWT with Net. Beans – Setting properties and layout

Advanced Topics • Using Swing/ AWT with Net. Beans – Setting properties and layout – Creating call-back methods • Inner Classes Copyright by Michael P. F. Fung 76