1 / 46

A Quick Java Course Part 2

A Quick Java Course Part 2. Michael McDougall CIS 573 September 29, 1999. Outline. More Basic Java Exceptions Packages This Static fields and methods Nice Java tricks Javadoc Serializing GUI Programming Command-line vs. Event-driven applications Painting the screen. Exceptions.

dora
Télécharger la présentation

A Quick Java Course Part 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A Quick Java CoursePart 2 Michael McDougall CIS 573 September 29, 1999

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

  3. Exceptions • Exceptions are used to signal errors that can’t or shouldn’t be handled by normal data flow. • Example: imagine a method div(x,y) which returns x/y. What do we return if y=0? • 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 • If an exception is thrown it percolates back up the call stack until it encounters a catch that matches the type of the exception. • The finally block gets executed whether an exception is thrown or not.

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

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

  9. Packages continued • 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 • 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 • 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 • 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. • 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. • Example: • int numOfPoints = Point.count; • Int d = Point.distance(p,q);

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

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

  17. Javadoc & documentation comments • Javadoc is a program that comes with the Java SDK. It generates HTML from java file. • Javadoc reads special comments called documentation comments and includes them in the HTML. • 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 • Now we use javadoc to generate HTML (-private means include private fields and classes): • %javadoc -private Point.java • Generates HTML files for Point, the class tree, index, etc.

  21. Documentation comment tags • Documentation comments can include tags, which javadoc uses when generating the HTML files. • Tags have the form: @<tagname> • Example: /** An elaborate Point. @author Bob @see BoolPoint */ class SpecialBoolPoint extends BoolPoint { ...

  22. Tags • Some tags that javadoc recognizes • @see getName :link to the javadoc for the getName method • @author Bill : the author of a class • @param x The input integer : gives information about a method parameter. • @return 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 • The Java Programming LanguageSecond Edition. Ken Arnold & James Gosling, Addison Wesley, 1998. • http://www.javasoft.com/products/jdk/1.2/docs/tooldocs/javadoc/index.html • The javadoc documentation

  25. Serializing • The java.io package has methods that let you write objects to files so that they can be loaded later. • 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 • 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.) • readObject() just does the reverse. • If writeObject() finds a field that is not serializable it will throw an exception.

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

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

  32. References • http://java.sun.com/docs/books/tutorial/uiswing/index.html. A tutorial about Swing.

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

  34. Event driven programs cont. • Event driven programs (like GUI Programs, Servers) have a different form. Start Initialize Wait Process Event Terminate

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

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

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

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

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

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

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

  42. Painting the screen continued • In the Java Swing library the javax.swing.JComponent class is the superclass for most window classes. • 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 Repaint Event … L=new Line(p1,p2); repaint(); … void paint(Graphics g) { drawLine(L); } Wait Wait

  45. Repainting • 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

More Related