Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that...
-
Upload
amie-charles -
Category
Documents
-
view
212 -
download
0
Transcript of Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that...
Graphics in Java
CS 21b
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
Exampleimport java.awt.*;
import java.applet.Applet;
public class HelloAgain extends Applet {
public void paint(Graphics g) {
g.drawString(“Hello”,50,50);
}
}
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
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
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
Listeners in Java
CS 21b
Listeners ActionListener
used for button and text field events refer to discussion on event models
for examples WindowListener
when windows are closed, minimized, etc
Listeners, continued
MouseListener when the mouse is clicked, pressed,
or released MouseMotionListener
when the mouse is moved or dragged
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
Associating Listenersto 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
WindowListener Methods void WindowActivated(WindowEvent) void WindowClosed(WindowEvent) void WindowClosing(WindowEvent) void WindowDeactivated(WindowEvent) void WindowDeiconified(WindowEvent) void WindowIconified(WindowEvent) void WindowOpened(WindowEvent)
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)
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
});
MouseListener Methods
void MouseClicked(MouseEvent) void MouseEntered(MouseEvent) void MouseExited(MouseEvent) void MousePressed(MouseEvent) void MouseReleased(MouseEvent)
MouseMotionListener Methods
void MouseMoved(MouseEvent) void MouseDragged(MouseEvent)
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
Mouse Adapter Classes MouseAdapter
implements MouseListener {} definitions for all methods
MouseMotionAdapter implements MouseMotionListener {} definitions for all methods
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
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
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
Exceptions
CS 21b
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
Try-catch Statement Syntax:
try { … } catch(Exception e) { ... } Example:
try {
System.out.println(5/x);
} catch(Exception e) {
System.out.println(“/ by zero”);
}
Breaking out of the try Blocktry { statement1; statement2; // if exception occurs here, // statement3 will be skipped statement3;} catch(Exception e) { statement4; // executed after exception
occurs}
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
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
Try-catch Chaintry { …
}
catch(SomeException se) { …
}
catch(AnotherException ae) { …
}
catch(YetAnotherException yae) { …
}
…
Files
CS 21b
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
Input/Output Classesin 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
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
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
Exceptions File operations throw exceptions so
make sure statements are enclosed in a try-catch statement
Exceptions thrown: IOException Common (specific) exception:
FileNotFoundException
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”)
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
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
Threads
CS 21b
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
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”
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)
run() Methodfor PrintThreadpublic class PrintThread extends Thread {...
public void run() {System.out.println(name);try { sleep(timedelay); }catch(Exception e) {}System.out.println(name);
}…}
Using PrintThreadPrintThread 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
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())
MovingCircle class (attributes & paint())// sample animation using Threadspublic class MovingCircle extends Applet {
int xpos = 5; // these variables will be updatedint size = 10; // on a different thread
...public void paint(Graphics g) {
g.drawOval(xpos,50,size,size);}
…}
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
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()
Networking
CS 21b
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
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
Networking in Java java.net package
import java.net.*; Most important classes
Socket ServerSocket URL (discussed earlier)
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
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
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
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
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