Download presentation
Presentation is loading. Please wait.
Published byAmie Charles Modified over 9 years ago
1
Graphics in Java CS 21b
2
The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets, panels, and frames Takes a Graphics object as a parameter signature: void paint(Graphics g) Graphics class contains drawing methods
3
Example import java.awt.*; import java.applet.Applet; public class HelloAgain extends Applet { public void paint(Graphics g) { g.drawString(“Hello”,50,50); }
4
The Graphics class Methods: drawing commands such as drawOval(int x, int y, int width, int height) setColor(Color c) fillOval(int x, int y, int width, int height) For a complete listing of available methods, javap java.awt.Graphics
5
About paint() Describes “current” picture Not cumulative if variables are used as arguments to the drawing commands, and the variables are updated, the drawing changes repaint() method called to explicitly update drawing called automatically every few seconds
6
Animation Example paint() defined as follows: public void paint(Graphics g) { g.drawString(“Hello”,x, 50); } init() with code that updates x: x += 5; repaint(); effect: String “moves” to the right
7
Listeners in Java CS 21b
8
Listeners ActionListener used for button and text field events refer to discussion on event models for examples WindowListener when windows are closed, minimized, etc
9
Listeners, continued MouseListener when the mouse is clicked, pressed, or released MouseMotionListener when the mouse is moved or dragged
10
Listeners are Interfaces A listener imposes on the implementing class that particular methods be defined To find out what methods need to be implemented, use javap e.g., javap java.awt.event.MouseListener
11
Associating Listeners to Visual Objects Use addxyzListener() methods associate listener objects to visual components called on the visual object that needs listening to takes a listener object as a parameter Effect: a method on the listener object is invoked when an event occurs on the visual object
12
WindowListener Methods void WindowActivated(WindowEvent) void WindowClosed(WindowEvent) void WindowClosing(WindowEvent) void WindowDeactivated(WindowEvent) void WindowDeiconified(WindowEvent) void WindowIconified(WindowEvent) void WindowOpened(WindowEvent)
13
WindowAdapter Class that implements WindowListener and provides defaults definitions for the methods Default definition: { } When creating a listener, instantiate the adapter and then override the methods of interest (using anonymous classes)
14
Example: Closing a Frame // in the constructor... addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } // no need to define the other methods });
15
MouseListener Methods void MouseClicked(MouseEvent) void MouseEntered(MouseEvent) void MouseExited(MouseEvent) void MousePressed(MouseEvent) void MouseReleased(MouseEvent)
16
MouseMotionListener Methods void MouseMoved(MouseEvent) void MouseDragged(MouseEvent)
17
Mouse Event Represents the state of the mouse pointer when the event occurs Most useful methods: getX() and getY() returns the coordinates of the mouse
18
Mouse Adapter Classes MouseAdapter implements MouseListener {} definitions for all methods MouseMotionAdapter implements MouseMotionListener {} definitions for all methods
19
Example: Dragging a Circle In paint(), g.drawCircle(x, y, 10, 10); Define: MousePressed(): compare mouse pointer coordinates with x and y, and check if circle was “selected” MouseDragged(): update x and y so that the circle “moves” with the mouse
20
The Applet as Listener Make the applet implement MouseListener and MouseMotionListener In init(), addMouseListener(this); addMouseMotionListener(this); define all seven mouse methods as methods of the applet
21
Third-Party Listeners and Adapters In init(), create separate MouseListener and MouseMotionListener objects instantiate the corresponding adapters and then, using anonymous classes, define only the methods you care to define associate these listeners to the applet
22
Exceptions CS 21b
23
Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that does not exist Java provides a way to handle exceptions that are thrown: the try-catch statement
24
Try-catch Statement Syntax: try { … } catch(Exception e) {... } Example: try { System.out.println(5/x); } catch(Exception e) { System.out.println(“/ by zero”); }
25
Breaking out of the try Block try { statement1; statement2; // if exception occurs here, // statement3 will be skipped statement3; } catch(Exception e) { statement4; // executed after exception occurs }
26
Why Use Try-catch ? Alternative: if-statement will be complex and hard to read if there are several exceptions what if the exception occurs within a loop ? (will need to worry about breaking out of the loop) Using try-catch is a more robust and structured way of handling exceptions
27
Exception Classes Classes that extend the Exception class Allows the programmer to be more specific about the exception: try { … } catch (ArithmeticException e) { … } Useful in a try-catch chain
28
Try-catch Chain try { … } catch(SomeException se) { … } catch(AnotherException ae) { … } catch(YetAnotherException yae) { … } …
29
Files CS 21b
30
File Unit of secondary storage Stores a sequence of bytes/characters Stream operations: read from stream, write to stream Associated with a filename Often organized under a directory hierarchy
31
Input/Output Classes in Java I/O viewed as a stream of bytes parent classes: InputStream, OutputStream As a stream of (Unicode) characters parent classes: Reader, Writer Need to import java.io.*; * An application employing files will use a subclass of one of the above classes
32
Text Files To create a text file, use PrintStream f = new PrintStream(new FileOutputStream(“filename.txt”)); To write to the text file use print methods f.println(…); // use like System.out Make sure to close the file before exiting the program f.close(); // ensures contents are updated
33
Text Files, continued To read from text files, use either DataInputStream or BufferedReader f = new DataInputStream( FileInputStream(“filename.txt”)); f = new BufferedReader(new FileReader(“filename.txt”)); Use read methods to read from file s = f.readLine(); // reads a string
34
Exceptions File operations throw exceptions so make sure statements are enclosed in a try-catch statement Exceptions thrown: IOException Common (specific) exception: FileNotFoundException
35
Reading a File from the Web Use URL class from java.net To open, wpage = new URL(address); f = new BufferedReader(new InputStreamReader(wpage.openStream())) ); * address is a String specifying the webpage address (e.g., “http://www.admu.edu.ph”)
36
Binary Files Text files are often sufficient but sometimes we want to store objects as they are (not their text forms) in a file Use ObjectOutputStream and ObjectInputStream operations: writeObject() and readObject() common technique: store objects in a Vector and then save the Vector in the file
37
java.io.* Summary There is a host of classes under this package that serve a variety of purposes Hints: use “javap java.io.classname” to find out available constructors and methods you often need to use FileInputStream, FileOutputStream, FileReader, and FileWriter to associate a name to the file
38
Threads CS 21b
39
Threads in Java Definition unit of program control that represents an execution sequence Java supports multi-threaded execution * Programs we have written up to this point have been on a single thread of control
40
The Thread class Thread creation instantiate a class that extends Thread instantiate the class Thread but provide a run() method Thread execution let t refer to a thread object t.start() causes the thread to execute its run() method “in the background”
41
Example 1: PrintThread PrintThread class extends Thread Attributes: name & timedelay Constructor sets name and timedelay run method prints name twice but with a time delay in between the print statements use Thread method sleep(timedelay)
42
run() Method for PrintThread public class PrintThread extends Thread {... public void run() { System.out.println(name); try { sleep(timedelay); } catch(Exception e) {} System.out.println(name); } … }
43
Using PrintThread PrintThread t1,t2,t3; t1 = new PrintThread("tic",5000); t2 = new PrintThread("tac",1000); t3 = new PrintThread("toe",3000); t1.start(); t2.start(); t3.start(); // expected output ? last output line should be tic
44
Example 2: MovingCircle MovingCircle class extends Applet Attributes: xpos & size (of circle) provide initial values paint() method: draws the circle Thread created inside init() run() method has a loop that continuously updates xpos & size and then repaints A button executes the thread (t.start())
45
MovingCircle class (attributes & paint()) // sample animation using Threads public class MovingCircle extends Applet { int xpos = 5; // these variables will be updated int size = 10; // on a different thread... public void paint(Graphics g) { g.drawOval(xpos,50,size,size); } … }
46
MovingCircle class (thread code) t = new Thread() { public void run() { while (xpos < 80) { try {sleep(1000);} catch(Exception e) {} xpos +=5; size += 3; repaint(); // forces paint() to be re- executed } }}; // this statement placed inside the init() method
47
The Runnable Interface Runnable is an interface that contains the run() method One of the constructors for Thread: public Thread(Runnable r) Can create a thread by giving it an argument (object) that implements run() alternative to extending thread and then overriding run()
48
Networking CS 21b
49
Client/Server Computing Communication over the network often occurs between a client and a server A server listens for connection requests and then responds to messages A client establishes a connection to a server and then sends messages TCP/IP: abstract layer that simplifies the above activities
50
Hosts, Ports, and Sockets Computers on the network are (uniquely) specified by a host name or an IP address Communication between hosts occurs through their ports each port allows several connections Socket connection handle that facilitates communication over the network
51
Networking in Java java.net package import java.net.*; Most important classes Socket ServerSocket URL (discussed earlier)
52
The Socket class Constructor requires a host and port that the client intends to connect to Useful Socket methods InputStream getInputStream() OutputStream getOutputStream() Use file/stream interfaces to carry out the communication
53
The ServerSocket class Constructor requires a port number that the server wishes to listen from accept() method returns a Socket object once a connection from a client has been established blocks (hangs) until the connection occurs
54
On the Server Program... Create a ServerSocket object specify port Invoke accept() on that object Obtain Socket object returned by accept() Obtain I/O streams from the socket carry out communication using these streams
55
On the Client Program... Create Socket object specify host and port of server Obtain I/O streams from the socket carry out communication using these streams * execute the server before the client
56
Allowing Multiple Connections to a Server Use Threads Have a loop that continuously calls accept() main thread Create and start a thread whenever accept() returns a socket facilitate communication on the socket using a separate thread
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.