Presentation is loading. Please wait.

Presentation is loading. Please wait.

A Quick Java Course Part 2 Michael McDougall CIS 573 September 29, 1999.

Similar presentations


Presentation on theme: "A Quick Java Course Part 2 Michael McDougall CIS 573 September 29, 1999."— Presentation transcript:

1 A Quick Java Course Part 2 Michael McDougall CIS 573 September 29, 1999

2 Outline n More Basic Java –Exceptions –Packages –This –Static fields and methods n Nice Java tricks –Javadoc –Serializing n GUI Programming –Command-line vs. Event-driven applications –Painting the screen

3 Exceptions n Exceptions are used to signal errors that can’t or shouldn’t be handled by normal data flow. n Example: imagine a method div(x,y) which returns x/y. What do we return if y=0? n Answer: any integer we return might be misinterpreted. Instead we throw an exception.

4 Exceptions example class ZeroDivisor extends Exception {} class Div { public int div(int x, int y) throws ZeroDivisor { if (y!=0) { return x/y; } else { throw new ZeroDivisor(); }

5 Exceptions example cont.... Div d = new Div(); try { int q = d.div(12,4); } catch (ZeroDivisor ex) { System.out.print( “Tried to divide by zero”); } finally { //always executed System.out.print(“Done”); }

6 Try, catch and finally n If an exception is thrown it percolates back up the call stack until it encounters a catch that matches the type of the exception. n The finally block gets executed whether an exception is thrown or not.

7 Packages n Java has an enormous amount of pre- defined classes (~1500 in jdk1.2). n For convenience classes are grouped into packages. n Examples: –java.util.Vector –java.security.PrivateKey n You can create your own packages.

8 How to use classes in packages n Classes in packages can be used just like other classes. You just have to specify the package along with the class name. n Example: –java.util.Vector v = new java.util.Vector();

9 Packages continued n If you get sick of writing java.blah.blah… all the time you can use import at the top of your file. //top of file import java.util.*; import java.security.PrivateKey; … Vector v = new Vector(); PrivateKey k = new PrivateKey();

10 This n Often an object needs a way to refer to itself. It can do so by using the this keyword.

11 This continued Class Foo { public void drawPoint(Point p) { …} } Class Point { public void draw() { Foo f = new Foo(); f.drawPoint(this); }

12 Static fields n Usually each object has its own copy of all its fields. A static field is shared by all members of a class. Class Point { public static int count =0; public Point() { count ++; }

13 Static methods n Methods can be declared static too. Static methods can only refer to static fields and methods. Class Point { public static float distance(Point p1, Point p1) { return sqrt(…); }

14 Static fields & methods cont. n Since static fields and methods are the same for all instances of a class you don’t actually need to create an instance to use them. n Example: –int numOfPoints = Point.count; –Int d = Point.distance(p,q);

15 Static field example n When we write: System.out.print(“Hi”); “out” is a static field of the System class.

16 Nice Java Tricks n Javadoc – generating documentation for your java code. n Serializing – writing objects to files.

17 Javadoc & documentation comments n Javadoc is a program that comes with the Java SDK. It generates HTML from java file. n Javadoc reads special comments called documentation comments and includes them in the HTML. n Javadoc allows you to document your code without maintaining a separate file.

18 Documentation comments Documentation comments always always take the form : /** blah blah */

19 Documentation comments example /** Stores a point in the plane.*/ public class Point { /** the x-coordinate */ public int x; /** the y-coordinate */ public int y; /** Constructs from two integers */ public Point(int a, int b) { x=a;y=b; } /** returns the sum of the coordinates */ public int sum() { return x+y;} }

20 Javadoc example n Now we use javadoc to generate HTML (-private means include private fields and classes): n %javadoc -private Point.java n Generates HTML files for Point, the class tree, index, etc.Point

21 Documentation comment tags n Documentation comments can include tags, which javadoc uses when generating the HTML files. n Tags have the n Example: /** An elaborate BoolPoint */ class SpecialBoolPoint extends BoolPoint {...

22 Tags n Some tags that javadoc recognizes getName :link to the javadoc for the getName method Bill : the author of a class x The input integer : gives information about a method parameter. A new point :gives information about the returned value.

23 Tags cont. version 3.6 : the version of the class. exception BadArg thrown if the argument is bad : information about the exceptions that are thrown by a method.

24 More about javadoc n The Java Programming Language Second Edition. Ken Arnold & James Gosling, Addison Wesley, n 2/docs/tooldocs/javadoc/index.html 2/docs/tooldocs/javadoc/index.html –The javadoc documentation

25 Serializing n The java.io package has methods that let you write objects to files so that they can be loaded later. n If a class implements the java.io.Serializable interface then you can use the writeObject method of java.io.ObjectOutputStream to convert an object to bytes.

26 Serializing example Class Point implements java.io.Serializable { public int x; public int y; public Point(int a, int b) { x=a; y=b; }

27 Serializing example: saving String fileName = “pointfile”; java.io.FileOutputStream outStream = new java.io.FileOutputStream(fileName); java.io.ObjectOutputStream objOutStream = new java.io.ObjectOutputStream(outStream); Point point = new Point(2,3); objOutStream.writeObject(point); objOutStream.close();

28 Serializing example:loading String fileName = “pointfile”; java.io.FileInputStream inStream = new java.io.FileInputStream(fileName); java.io.ObjectInputStream objInStream = new java.io.ObjectInputStream(inStream); Point point = (Point) objInStream.readObject(); objInStream.close();

29 Serializing continued n writeObject() recursively writes all the member fields of an object (including the fields of the fields, the fields of the fields of the fields, etc.) n readObject() just does the reverse. n If writeObject() finds a field that is not serializable it will throw an exception.

30 Serializing continued n writeObject will work on almost all classes automatically. n Some classes have fields which need special treatment. You have to write special methods for such classes.

31 GUI Programming Outline n Command-line programs vs. GUI- programs –Event driven paradigm –Why events are tricky n Painting the screen

32 References n iswing/index.html. A tutorial about Swing. iswing/index.html

33 Event driven programs n Most ‘command-line’ programs have the following form. Start Process Data Print Result Terminate OSYour Code OS Your Code

34 Event driven programs cont. n Event driven programs (like GUI Programs, Servers) have a different form. StartInitializeWait Terminate Process Event

35 GUI Events n Possible events: –New HTTP request –Clock Tick –“B” key pressed –Mouse Button Down n GUI Programs typically have a large number of possible events.

36 Maintaining a stable state n Event-driven programs must leave the computer in a reasonable state whenever you finish processing an event. n This can be tricky if there are a lot of possible events; it is hard to account for all possible streams of events. n Often an unexpected combination of events will make a GUI program go bad.

37 Event steam example: drawing a line. n Say you want your program to draw a line from one point to another using the mouse and the left mouse button. n Expected event sequence: 1.Left mouse button down 2.Mouse move 3.… 4.Mouse move 5.Left mouse button up

38 Drawing a line continued n The programmer has to implement what happens after each event. n Example: –Button Down -> oldPoint := mousePosition –Mouse Move -> do nothing –Button Up -> create line from oldPoint to mousePosition

39 Possible problems n What if there is no movement? Do you create an empty line? n What if the user switches to another window before the “Button Up” message never arrives? n What if the keyboard or other mouse buttons are pressed?

40 Robust Applications n Moral of the story: designing an application that can handle all possible combinations of events can be very difficult. n Things that could help: –A Spin-like specification and some way of verifying it –Conservative programming

41 Painting the Screen n Drawing on the screen is too slow to be done constantly. n Instead, the operating system redraws parts of the screen as necessary. n Typically the GUI Program receives a “paint” message when the screen should be refreshed.

42 Painting the screen continued n In the Java Swing library the javax.swing.JComponent class is the superclass for most window classes. n When the Operating System wants to repaint the screen the JComponent.paint() method is called.

43 Paint method example public void paintComponent(Graphics inG) { Point startPoint = getStartDragPoint(); Point endPoint = getCurrentDragPoint(); inG.setColor(Color.blue); inG.drawRect(startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y); }

44 Interacting With the Screen Button Pressed Event … L=new Line(p1,p2); repaint(); … void paint(Graphics g) { drawLine(L); } Wait Repaint Event Wait

45 Repainting n If you know that the screen is out of date and should be refreshed you can call JComponent.repaint(). This ensures that the window will be repainted sometime in the future.

46 Concurrency


Download ppt "A Quick Java Course Part 2 Michael McDougall CIS 573 September 29, 1999."

Similar presentations


Ads by Google