Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that...

56
Graphics in Java CS 21b

Transcript of Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that...

Page 1: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Graphics in Java

CS 21b

Page 2: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 3: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Exampleimport java.awt.*;

import java.applet.Applet;

public class HelloAgain extends Applet {

public void paint(Graphics g) {

g.drawString(“Hello”,50,50);

}

}

Page 4: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 5: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 6: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 7: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Listeners in Java

CS 21b

Page 8: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Listeners ActionListener

used for button and text field events refer to discussion on event models

for examples WindowListener

when windows are closed, minimized, etc

Page 9: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Listeners, continued

MouseListener when the mouse is clicked, pressed,

or released MouseMotionListener

when the mouse is moved or dragged

Page 10: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 11: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 12: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

WindowListener Methods void WindowActivated(WindowEvent) void WindowClosed(WindowEvent) void WindowClosing(WindowEvent) void WindowDeactivated(WindowEvent) void WindowDeiconified(WindowEvent) void WindowIconified(WindowEvent) void WindowOpened(WindowEvent)

Page 13: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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)

Page 14: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

});

Page 15: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

MouseListener Methods

void MouseClicked(MouseEvent) void MouseEntered(MouseEvent) void MouseExited(MouseEvent) void MousePressed(MouseEvent) void MouseReleased(MouseEvent)

Page 16: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

MouseMotionListener Methods

void MouseMoved(MouseEvent) void MouseDragged(MouseEvent)

Page 17: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 18: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Mouse Adapter Classes MouseAdapter

implements MouseListener {} definitions for all methods

MouseMotionAdapter implements MouseMotionListener {} definitions for all methods

Page 19: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 20: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 21: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 22: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Exceptions

CS 21b

Page 23: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 24: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Try-catch Statement Syntax:

try { … } catch(Exception e) { ... } Example:

try {

System.out.println(5/x);

} catch(Exception e) {

System.out.println(“/ by zero”);

}

Page 25: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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}

Page 26: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 27: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 28: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Try-catch Chaintry { …

}

catch(SomeException se) { …

}

catch(AnotherException ae) { …

}

catch(YetAnotherException yae) { …

}

Page 29: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Files

CS 21b

Page 30: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 31: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 32: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 33: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 34: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Exceptions File operations throw exceptions so

make sure statements are enclosed in a try-catch statement

Exceptions thrown: IOException Common (specific) exception:

FileNotFoundException

Page 35: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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”)

Page 36: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 37: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 38: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Threads

CS 21b

Page 39: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 40: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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”

Page 41: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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)

Page 42: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

run() Methodfor PrintThreadpublic class PrintThread extends Thread {...

public void run() {System.out.println(name);try { sleep(timedelay); }catch(Exception e) {}System.out.println(name);

}…}

Page 43: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 44: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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())

Page 45: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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);}

…}

Page 46: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 47: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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()

Page 48: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Networking

CS 21b

Page 49: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 50: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 51: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

Networking in Java java.net package

import java.net.*; Most important classes

Socket ServerSocket URL (discussed earlier)

Page 52: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 53: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 54: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 55: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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

Page 56: Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,

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