Introduction to Computing Using Java Exception Handling, Array & GUI 1 Copyright by Michael P.F. Fung 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! 2 Copyright by Michael P.F. Fung Exceptionally Ugly 3 Copyright by Michael P.F. Fung 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, ArithmeticException, 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). 4 Copyright by Michael P.F. Fung 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(); 5 Copyright by Michael P.F. Fung 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); } Normal return 6 Copyright by Michael P.F. Fung 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); } Abnormal return “throwing exception” 7 Copyright by Michael P.F. Fung 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 8 Copyright by Michael P.F. Fung 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; } 9 Copyright by Michael P.F. Fung 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); } 10 Copyright by Michael P.F. Fung 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; } } 11 Copyright by Michael P.F. Fung 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 wow, skipped } } 12 Copyright by Michael P.F. Fung 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 wow, skipped } double result = value + 19 * 97 - 2002; } • It avoids skipping the rest statements in the whole method body! i.e. rescuing the method. 13 Copyright by Michael P.F. Fung Twins: Detection and Handling • In fact, try and catch are twins. • Try is responsible for detection. • Catch is responsible for identification and handling. 14 Copyright by Michael P.F. Fung 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 wow, skipped … } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); value = 3.14159; } // the program continues normally hereafter } 15 Copyright by Michael P.F. Fung Handling Exceptions • We catch certain type of exception by: catch (ExceptionType 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. 16 Copyright by Michael P.F. Fung Catching Several Kinds of Possible Exceptions double tan(double angle) throws IOException, ArithmeticException { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new ArithmeticException(); } … void main(…) { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3.14159; // wow wow, skipped } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); value = 3.14159; } catch (ArithmeticException arithmetic_exception_object_ref) { System.out.println(“Arithmetic Exception received!”); value = 0.0; } // the program continues normally hereafter } 17 Copyright by Michael P.F. Fung 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. 18 Copyright by Michael P.F. Fung Exception Propagation double tan(double angle) throws IOException, ArithmeticException { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new ArithmeticException(); } … void main(…) throws ArithmeticException { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3.14159; // wow 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; } // ArithmeticException is not caught // this method terminates and propagates the arithmetic exception object // on receiving ArithmeticException } 19 Copyright by Michael P.F. Fung 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. 20 Copyright by Michael P.F. Fung 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]; 21 Copyright by Michael P.F. Fung Declaration and Array Creation int[] i = new int[1000]; is equivalent to int[] i; i = new int[1000]; // i is nothing yet // i keeps something 22 Copyright by Michael P.F. Fung 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]. 23 Copyright by Michael P.F. Fung Syntax of Creating Arrays type[] array_name = new type[length]; type[] array_name = {value1, value2, ...}; e.g. double[] String[] String char[] GPA = new double[50]; countryCode = 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. 24 Copyright by Michael P.F. Fung 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] ArrayIndexOutOfBoundsException • To get the length (size) of an array: – vowels.length – NOT vowel.length() [confused with String] 25 Copyright by Michael P.F. Fung Example: The Parameter in main() class TestArgs { 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:\LetSee\> There are 0 C:\LetSee\> There are 2 Apple Orange java TestArgs arguments: java TestArgs Apple Orange arguments: 26 Copyright by Michael P.F. Fung 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. 27 Copyright by Michael P.F. Fung 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 28 Copyright by Michael P.F. Fung 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(); 29 Copyright by Michael P.F. Fung Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) ? ? ? Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 30 Copyright by Michael P.F. Fung Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) ?? Octopus (class) Octopus (object) Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 31 Copyright by Michael P.F. Fung Array Itself is Also a Reference deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) ? Octopus (class) Octopus (object) Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 32 Copyright by Michael P.F. Fung Array Itself is Also a Reference Octopus (object) deck[ ] (reference) Octopus (class) Octopus (object) deck[2] (reference) deck[1] (reference) deck[0] (reference) Class type array Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); 33 Copyright by Michael P.F. Fung Array Itself is Also a Reference i[ ] (reference) Primitive type array Class type array 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 Copyright by Michael P.F. Fung Assignment of the Whole Array i[ ] (reference) j[ ] (reference) 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 Copyright by Michael P.F. Fung Assignment of the Whole Array i[ ] (reference) j[ ] (reference) j[4] j[3] j[2] (int) j[1] (int) j[0] 0(int) 0(int) 0(int) 00 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 Copyright by Michael P.F. Fung Assignment of the Whole Array i[ ] (reference) j[ ] (reference) j[4] j[3] j[2] (int) j[1] (int) j[0] 0(int) 0(int) 0(int) 00 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 Copyright by Michael P.F. Fung New Concept: Primitive Type Array Argument Passing class Student { public static void studyHard(double[] newGPAs) { newGPAs[0] = 4.0; newGPAs[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.studyHard(GPAs); System.out.println(GPAs[0]); System.out.println(GPAs[1]); } newGPAs (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 toMichael 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 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 initialSalary) { salary = initialSalary; } } victims (reference) Employee (object) salary 1000 TAs[0] (reference) Employee (object) TAs[1] (reference) Employee (object) salary 2000 salary 5000 TAs[2] (reference) 39 Copyright by Michael P.F. Fung Table (2-Level Array) What’s the type? double // There are 176 students, 8 assignments // record their marks in double double[][] mark = new double[176][8]; mark[6][0] = 99.34; // mark: 7th student, Asg1 mark[175][6] = 89.12; // mark: last student, Asg7 double[] double[] singleStudent; singleStudent = mark[175]; // refer to the singleStudent[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. 40 Copyright by Michael P.F. Fung Table Illustrated mark[ ][ ] (reference) Array of Array of double mark[2] mark[1] mark[0] (reference) (reference) (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 Copyright by Michael P.F. Fung 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]; 42 Copyright by Michael P.F. Fung Duplicating an int Array i[ ] (reference) j[ ] (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]; 43 Copyright by Michael P.F. Fung Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 j[ ] (reference) j[2] (int) 0 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 Copyright by Michael P.F. Fung Duplicating an int Array i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 j[ ] (reference) j[2] (int) 9 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 Copyright by Michael P.F. Fung Duplicating an Object Array deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus (class) Octopus (object) Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; 46 Copyright by Michael P.F. Fung Duplicating an Object Array newDeck[ ] (reference) ? deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus (class) Octopus (object) Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; 47 Copyright by Michael P.F. Fung Duplicating an Object Array newDeck[ ] (reference) newDeck[2] (reference) newDeck[1] (reference) newDeck[0] (reference) deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus (class) Octopus (object) Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; 48 Copyright by Michael P.F. Fung Duplicating an Object Array newDeck[ ] (reference) newDeck[2] (reference) newDeck[1] (reference) newDeck[0] (reference) deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus (object) Octopus (class) Only the object references are copied! Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; 49 Copyright by Michael P.F. Fung 7-Minute Break 50 Copyright by Michael P.F. Fung Graphics User Interface(GUI) • Graphical User Interface • Basic Elements • Event Driven Model • Trigger and Callback 51 Copyright by Michael P.F. Fung Command-line User Interface 52 Copyright by Michael P.F. Fung Graphical User Interface 53 Copyright by Michael P.F. Fung 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 54 Copyright by Michael P.F. Fung GUI – User Input • Use of various interactive input devices – – – – Keyboard Mouse Touch screen … • To gather command and control from user – A mouse click opens a file – A mouse drag moves a window – Pressing <Enter> means “OK” 55 Copyright by Michael P.F. Fung 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); 56 Copyright by Michael P.F. Fung 1) Store State • Basic properties – Colour – Size – Visibility • Dynamic states – On/off state of a button – Value of a text field 57 Copyright by Michael P.F. Fung 2) Perform Action Paint the window Draw circles Display text 58 Copyright by Michael P.F. Fung 3) Generate Event Detect if you dragged the scrollbar Detect if you clicked a button Detect if you dragged the mouse pointer 59 Copyright by Michael P.F. Fung 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. 60 Copyright by Michael P.F. Fung 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 – TextField… 61 Copyright by Michael P.F. Fung 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 SimpleGUI { public static void main(String[] args) { Frame myWindow = new Frame(); myWindow.setTitle("Simple GUI"); myWindow.setSize(200, 100); myWindow.setVisible(true); } } 62 Copyright by Michael P.F. Fung Components List - Classes 63 Copyright by Michael P.F. Fung 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 64 Copyright by Michael P.F. Fung Component - Basic Properties • Colour : setBackground(Color) setForeground(Color) • Size : setSize(int, int) • Position : setLocation(int, int) • State : setEnabled(boolean) • Font : setFont(Font) • Visibility : setVisible(boolean) • … 65 Copyright by Michael P.F. Fung Component - Relationship • Sibling/sub-ordinary relationship Button1 and Button2 are contained/embedded in the Frame window.add(button1); Button1 is on the left of Button2 on the same row • Relative position between the components 66 Copyright by Michael P.F. Fung 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. 67 Copyright by Michael P.F. Fung Component - Event Listening • To listen to an event, we need a listener: Frame myWindow = new Frame(); /* Adapter is a kind of Listener */ WindowAdapter adapter = new WindowAdapter(); myWindow.addWindowListener(adapter); • add*Listener() are methods of components. • We register a listener to listen to certain kind of events, say MouseEvent. – e.g. MouseListener may be MouseAdapter objects. 68 Copyright by Michael P.F. Fung Event Handling Button1 User action Generates MouseEvent MouseListener MouseAdapter Event Handler may: - Update the appearance of the button - Modify the state of the button - Perform programmer-defined action such as “Say Hello” mouseClicked mouseEntered Event mousePressed Dispatching … 69 Copyright by Michael P.F. Fung Listener Example import java.awt.*; import java.awt.event.*; class ListenGUI { public static void main(String[] args) { Frame myWindow = new Frame(); myWindow.setTitle("Simple GUI"); myWindow.setSize(200, 100); myWindow.setVisible(true); myWindow.addWindowListener(new MyWindowAdapter()); } } File ListenGUI.java class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println(“Terminating the program!”); System.exit(1); // a message to ask the System to exit // ... OR you may open other windows!!! } } 70 Copyright by Michael P.F. Fung 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 MouseEvent which indicates mouse button pressed, the mousePressed() method of the MouseAdapter object will be invoked. 71 Copyright by Michael P.F. Fung Customizing the Handling • Without customizing (overriding) the default handler methods provided in the adapter, nothing would happen. • That’s why we extends the WindowAdapter, MouseAdapter… classes. • By re-defining (overriding) their methods, we can achieve desired behaviour in event handling. 72 Copyright by Michael P.F. Fung Examples • • • • • NormalMouseAdapter NormalWindowAdapter NormalGUI ListenGUI ListenGUI2 73 Copyright by Michael P.F. Fung What Kinds of Events? • Examples: – WindowEvent needs WindowListener. WindowAdapter is a kind of WindowListener. – MouseEvent needs MouseListener. MouseAdapter is a kind of MouseListener. • The events themselves are generated by some components under user interaction. 74 Copyright by Michael P.F. Fung 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. 75 Copyright by Michael P.F. Fung Advanced Topics • Using Swing/ AWT with NetBeans – Setting properties and layout – Creating call-back methods • Inner Classes 76 Copyright by Michael P.F. Fung