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

Slides:



Advertisements
Similar presentations
Exceptions. 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.
Advertisements

Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
1 Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
For IST410 Students only Events-1 Event Handling.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Intermediate Java1 An example that uses inner classes Week Four Continued.
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
GUI. Swing Class Hierarchy Swing Components Swing Conatiners  JFrame – top-level window to store components.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Networking with Java CSc 335 Object-Oriented Programming and Design Spring 2009.
Io package as Java’s basic I/O system continue’d.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java Programming: Guided Learning with Early Objects
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Object Persistence and Object serialization CSNB534 Asma Shakil.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Chapter 7: Pinball Game Construction Kit. Vectors Example of a “collection class” Must “import java.util.Vector” More flexible than arrays: will grow.
Object Oriented Programming.  Interface  Event Handling.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Chapter 5 Introduction to Defining Classes
Java Programming Review (Part II) Enterprise Systems Programming.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Distributed Systems CS Project 1: File Storage and Access Kit (FileStack) Recitation 1, Aug 29, 2013 Dania Abed Rabbou and Mohammad Hammoud.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
Threads CS 21b. Threads in Java zDefinition Õunit of program control that represents an execution sequence zJava supports multi-threaded execution * Programs.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts, IBM Corp Advanced Java Programming CSE 7345/5345/ NTU 531 Multithreaded/Sockets/Server Welcome.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
Computer Science 209 Graphics and GUIs.
I/O Basics.
GUI Event Handling Nithya Raman.
Events, Event Handlers, and Threads
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

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

Example import 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 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

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 Block try { 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 Chain try { … } 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 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

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., “

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

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

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

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