Chapter 14: Applets and More

Similar documents
8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

Chapter 14: Applets and More

G51PRG: Introduction to Programming Second semester Applets and graphics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Graphics Applets. By Mr. Dave Clausen


Unit 7: Event driven programming

Computer Science 210: Data Structures. Intro to Java Graphics

Java Applet Basics. Life cycle of an applet:

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

Graphics Applets. By Mr. Dave Clausen

User interfaces and Swing

9. APPLETS AND APPLICATIONS

Graphical User Interfaces 2

Chapter 7 Applets. Answers

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

Appendix F: Java Graphics

Appendix F: Java Graphics

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

Exam: Applet, Graphics, Events: Mouse, Key, and Focus

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

MULTIMEDIA PROGRAMMING IN JAVA. Prof.Asoc. Alda Kika Department of Informatics Faculty of Natural Sciences University of Tirana

CSIS 10A Assignment 14 SOLUTIONS

Lecture 3: Java Graphics & Events

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application

SIMPLE APPLET PROGRAM

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

PROGRAMMING LANGUAGE 2

AP CS Unit 12: Drawing and Mouse Events

Lecture 5: Java Graphics

Chapter 12 Advanced GUIs and Graphics

IT101. Graphical User Interface

Graphical User Interface (GUI)

CSC System Development with Java Introduction to Java Applets Budditha Hettige

Java Coordinate System

Introduction to Computer Science I

Graphical User Interfaces 2

Graphical User Interfaces 2

Chapter 3 - Introduction to Java Applets

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

Here is a list of a few of the components located in the AWT and Swing packages:

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Graphical User Interface (GUI)

Programming graphics

UNIT -1 JAVA APPLETS

Chapter 13. Applets and HTML. HTML Applets. Chapter 13 Java: an Introduction to Computer Science & Programming - Walter Savitch 1

CS 251 Intermediate Programming GUIs: Components and Layout

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

2IS45 Programming

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Programming Languages and Techniques (CIS120)

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Summary. 962 Chapter 23 Applets and Java Web Start

TWO-DIMENSIONAL FIGURES

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

public static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:

Introduction to Java Applets 12

Which of the following syntax used to attach an input stream to console?

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

CS 251 Intermediate Programming GUIs: Event Listeners

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

Class 16: The Swing Event Model

PESIT Bangalore South Campus

Part 3: Graphical User Interface (GUI) & Java Applets

GUI, Events and Applets from Applications, Part III

Programming Languages and Techniques (CIS120)

cs Java: lecture #5

Chapter 1 GUI Applications

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Graphics and Painting

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Java - Applets. public class Buttons extends Applet implements ActionListener

L4,5: Java Overview II

Come & Join Us at VUSTUDENTS.net

Packages: Putting Classes Together

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

CSCI 053. Week 5 Java is like Alice not based on Joel Adams you may want to take notes. Rhys Price Jones. Introduction to Software Development

Overview. Applets. A Java GUI inside your browser! Important methods Drawing images Playing audio Getting input parameters Double buffering

Programmierpraktikum

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

Advanced Internet Programming CSY3020

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

Programming: You will have 6 files all need to be located in the dir. named PA4:

CS2110. GUIS: Listening to Events

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

Windows and Events. created originally by Brian Bailey

Lecture 7 A First Graphic Program And Data Structures & Drawing

Higher National Diploma in Information Technology First Year, Second Semester Examination 2015

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Assignment 2. Application Development

Transcription:

Chapter 14: Applets and More Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All rights reserved.

Reading Quiz 2010 Pearson Addison-Wesley. All rights reserved.

Chapter Topics Chapter 14 discusses the following main topics: Introduction to Applets A Brief Introduction to HTML Creating Applets with Swing Using AWT for Portability Drawing Shapes Handling Mouse and Key Events Timer Objects Playing Audio 2010 Pearson Addison-Wesley. All rights reserved. 14-3

Introduction to Applets There are two types of programs you can create with Java: applications applets. An application is a stand-alone program that runs on your computer. Applets are Java programs that are usually part of a Web site. If a user opens the Web site with a Java-enabled browser, the applet is executed inside the browser window. 2010 Pearson Addison-Wesley. All rights reserved. 14-4

Introduction to Applets It appears to the user that the applet is part of the Web site. Applets are stored on a Web server along with the site s Web pages. Applets associated with a viewed web page are transmitted to the user s system. Once the applets are transmitted, the user s system executes them. Applets can be used to extend the capabilities of a Web page. 2010 Pearson Addison-Wesley. All rights reserved. 14-5

Introduction to Applets Web pages are normally written in Hypertext Markup Language (HTML). HTML is static content; whereas, applets are dynamic. An applet does not have to be on a web server in order to be executed. They can be stored on the local computer. 2010 Pearson Addison-Wesley. All rights reserved. 14-6

Applet Limitations Applets run on the user s system, not the server. For security purposes, applets can not: access the local computer file system, run any other program on the user s system. execute operating system procedures. retrieve information about the user or their system. make network connections with any system except the server from which the applet was transmitted. run anonymously. If an applet displays a window, it will automatically have a message such as Warning: Applet Window displayed in it. 2010 Pearson Addison-Wesley. All rights reserved. 14-7

Introduction to HTML Hypertext Markup Language (HTML) is the language that Web pages are written in. Hypertext can contain a link to other content on the web page, or another web page. A Markup Language allows you to mark up a text file by inserting special instructions. These instructions tell the browser how to format the text and create any hypertext links. To make a web page, create a text file: that contains HTML instructions (known as tags), the text that should be displayed on the Web page, and typically has a.html file extension. 2010 Pearson Addison-Wesley. All rights reserved. 14-8

Introduction to HTML This document is called an HTML document. The tags instruct the browser: how to format the text, where to place images, what to do when the user clicks on a link, etc. Most HTML tags have an opening tag and a closing tag. <tag_name>text</tag_name> The tags are enclosed in angle brackets (< >). The closing tag is preceded by a forward slash (/). 2010 Pearson Addison-Wesley. All rights reserved. 14-9

Document Structure Tags The <html></html> tag marks the beginning and ending of an HTML document. The tag <head></head> marks the document head, a section containing information about the document. The document head contains the <title> </title> tag, which is contains the title of the document. Example: BasicWebPage1.html 2010 Pearson Addison-Wesley. All rights reserved. 14-10

Document Structure Tags After the document head comes the <body></body> tag. The document body contains all of the tags and text that produce output in the browser. Example: BasicWebPage2.html 2010 Pearson Addison-Wesley. All rights reserved. 14-11

Text Formatting Tags There are many HTML tags that you can use to change the appearance of text. For example, there are six different header tags. <h1></h1> through <h6></h6> A level one header appears in boldface, and is much larger than regular text. A level two header also appears in boldface, but is smaller than a level one header. This pattern continues with the other header tags. 2010 Pearson Addison-Wesley. All rights reserved. 14-12

Text Formatting Tags Many tags allow an align attribute to be used to modify where the text shows on the web page: <h1 align="center">text</h1> <h1 align="left">text</h1> <h1 align="right">text</h1> An old way of centering text is to use the <center></center> tag to center a line of text. You can display text: in boldface <b></b>, and italics <i></i>. Example: BasicWebPage3.html 2010 Pearson Addison-Wesley. All rights reserved. 14-13

Breaks in Text The <br /> tag causes a line break to appear at the point in the text where it is inserted. Browsers usually ignore the newline characters that are created when you press the Enter key. The <p /> tag causes a paragraph break. A paragraph break typically inserts more space into the text than a line break. 2010 Pearson Addison-Wesley. All rights reserved. 14-14

Breaks in Text The <hr /> tag causes a horizontal rule to appear at the point in the text where it is inserted. A horizontal rule is a thin, horizontal line that is drawn across the web page. Example: BasicWebPage4.html 2010 Pearson Addison-Wesley. All rights reserved. 14-15

HTML Links A link is some element in a Web page that can be clicked on by the user. The tag that is used to insert a link has the following general format: <a href="address">text</a> The Text that appears between the opening and closing tags is the text that will be displayed in the web page. The web resource that is located at Address will be displayed in the browser. 2010 Pearson Addison-Wesley. All rights reserved. 14-16

HTML Links This address is a uniform resource locator (URL). The address is enclosed in quotation marks. Example: <a href="http://www.gaddisbooks.com">click here to go to the textbook's web site.</a> Example: LinkDemo.html 2010 Pearson Addison-Wesley. All rights reserved. 14-17

Checkpoint 1 2010 Pearson Addison-Wesley. All rights reserved.

Checkpoint 1 <title>my Web Page</title> in the head section <b><center>my Resume</center></b> <a href="http://java.sun.com">click Here</a> 2010 Pearson Addison-Wesley. All rights reserved.

Creating Applets With Swing Applets are very similar to the GUI applications. Instead of displaying its own window, an applet appears in the browser s window. The differences between GUI application code and applet code are: A GUI application class is derived from JFrame. An applet class is derived from JApplet. The JApplet class is part of the javax.swing package. A GUI application class has a constructor that creates other components and sets up the GUI. An applet class does not normally have a constructor. Instead, it has a method named init that performs the same operations as a constructor. 2010 Pearson Addison-Wesley. All rights reserved. 14-20

Creating Applets With Swing The differences are (continued): The following methods are not called in an applet: super setsize setdefaultcloseoperation pack setvisible No main method is needed to create an Applet object. The browser creates an instance of the class automatically. Example: SimpleApplet.java SimpleApplet.html 2010 Pearson Addison-Wesley. All rights reserved. 14-21

Running an Applet The process of running an applet is different from that of running an application. To run an applet, create an HTML document with an APPLET tag, which has the following general format: <applet code="filename.class" width="width_value" height="height_value"></applet> Don t forget the closing angle bracket. Attributes should be enclosed in quotes. 2010 Pearson Addison-Wesley. All rights reserved. 14-22

Running an Applet Filename.class is the compiled bytecode of the applet, not the.java file. You can optionally specify a path along with the file name. If you specify only the file name, it is assumed that the file is in the same directory as the HTML The browser: loads specified byte code, and executes it in an area that is the size specified by the width_value and height_value. 2010 Pearson Addison-Wesley. All rights reserved. 14-23

Using appletviewer The appletviewer program loads and executes an applet without the need for a Web browser. When running the program, specify the name of an HTML document as a command line argument. appletviewer SimpleApplet.html This command executes any applet referenced by an APPLET tag in the file SimpleApplet.html. If the document has more than one APPLET tag, it will execute each applet in a separate window. 2010 Pearson Addison-Wesley. All rights reserved. 14-24

Applet Event Handling Events in applets are handled with event listeners exactly as they are in GUI applications. Example: TempConverter.java TempConverter.html 2010 Pearson Addison-Wesley. All rights reserved. 14-25

Checkpoint 2 14.12 2010 Pearson Addison-Wesley. All rights reserved.

Checkpoint 2 14.12 JApplet init the browser creates an instance of the class 2010 Pearson Addison-Wesley. All rights reserved.

Using AWT for Portability AWT is the original library that has been part of Java since its earliest version. Swing is an improved library that was introduced with Java 2. Some browsers do not directly support the Swing classes in applets. These browsers require a plug-in to run swing applets. This plug-in is automatically installed on a computer when the Java SDK is installed. 2010 Pearson Addison-Wesley. All rights reserved. 14-28

Using AWT for Portability Other people running applets might not have the required plug-in. The AWT classes can be used instead of the Swing classes for the components in the applet. The AWT component classes: there is a corresponding AWT class for each of the Swing classes covered so far. The names of the AWT classes names do not start with the letter J. Example: AWTTempConverter.java, TempConverter.html 2010 Pearson Addison-Wesley. All rights reserved. 14-29

Drawing Shapes Components have an associated Graphics object that may be used to draw lines and shapes. Java allows drawing of lines and graphical shapes such as rectangles, ovals, and arcs. Frame or panels can become a canvas for your drawings. 2010 Pearson Addison-Wesley. All rights reserved. 14-30

XY Coordinates The location of each pixel in a component is identified with an X coordinate and a Y coordinate. The coordinates are usually written in the form (X, Y). Unlike Cartesian coordinates, the upper-left corner of a drawing area is (0, 0). The X coordinates increase from left to right, and the Y coordinates increase from top to bottom. When drawing a line or shape on a component, you must indicate its position using X and Y coordinates. 2010 Pearson Addison-Wesley. All rights reserved. 14-31

Graphics Objects Each component has an internal object that is derived from the Graphics class, which is part of the java.awt package. This object has numerous methods for drawing graphical shapes on the surface of the component. 2010 Pearson Addison-Wesley. All rights reserved. 14-32

Graphics Objects Some of the methods of the Graphics class: setcolor(color c) Sets the drawing color for this object. getcolor() Returns the current drawing color for this object. drawline(int x1, int y1, int x2, int y2) Draws a line on the component drawrect(int x, int y, int width, int height) Draws the outline of a rectangle on the component. filloval(int x, int y, int width, int height) Draws a filled oval. drawstring(string str, int x, int y) Draws the string passed into str using the current font. 2010 Pearson Addison-Wesley. All rights reserved. 14-33

Graphics Objects In order to call these methods, you must get a reference to a component s Graphics object. One way to do this is to override the paint method. You can override the paint method in any class that is derived from: JApplet JFrame Any AWT class The paint method is responsible for displaying, or painting, a component on the screen. 2010 Pearson Addison-Wesley. All rights reserved. 14-34

Graphics Objects The paint method is automatically called when the component is first displayed and any time the component needs to be redisplayed. The header for the paint method is: public void paint(graphics g) The method s argument is a Graphics object, which is automatically passed by the calling component. Overriding the paint method, allows drawing of graphics on the Graphics object argument. Example: LineDemo.java, LineDemo.html 2010 Pearson Addison-Wesley. All rights reserved. 14-35

Graphics Objects The Graphics object argument is responsible for drawing the entire applet window. It is advisable to call the base class paint method passing the Graphics object, g, as an argument: super.paint(g); g.setcolor(color.red); g.drawline(20, 20, 280, 280); This is a red diagonal line drawn from the top-left area of the applet window to the bottom-right area. 2010 Pearson Addison-Wesley. All rights reserved. 14-36

Rectangles Rectangles can be drawn or filled. g.drawrect(10, 10, 50, 50); g.fillrect(10, 10, 50, 50); The fillrect and drawrect take four integers as parameters: drawrect(int x, int y, int width, int height) Example: RectangleDemo.java RectangleDemo.html 2010 Pearson Addison-Wesley. All rights reserved. 14-37

Ovals and Bounding Rectangles Ovals are created by drawing the oval inside of a bounding rectangle. This rectangle is invisible to the viewer of the Graphics object. g.filloval(x, y, width, height); Width Example: OvalDemo.java OvalDemo.html (x,y) Height 2010 Pearson Addison-Wesley. All rights reserved. 14-38

Arcs Arcs are drawn from the 90 degree position counterclockwise and can be filled or unfilled g.drawarc(0, 20, 120, 120, 0, 90); g.fillarc(0, 20, 120, 120, 0, 90); The fillarc and drawarc take six integers as parameters: drawarc(int x, int y, int width, int height, int start, int end) Example: ArcDemo.java ArcDemo.html 2010 Pearson Addison-Wesley. All rights reserved. 14-39

Polygons Polygons are drawn using arrays of integers representing x, y coordinates int[]xcoords={60,100,140,140,100,60,20,20}; int[]ycoords={20,20,60,100,140,140,100,60}; 2010 Pearson Addison-Wesley. All rights reserved. 14-40

Polygons The fillpolygon and drawpolygon use the arrays as parameters: Example: PolygonDemo.java PolygonDemo.html 2010 Pearson Addison-Wesley. All rights reserved. 14-41

The repaint Method We do not call a component s paint method. It is automatically called when the component must be redisplayed. We can force the application or applet to call the paint method. repaint(); The repaint method clears the surface of the component and then calls the paint method. 2010 Pearson Addison-Wesley. All rights reserved. 14-42

Drawing on Panels To draw on a panel, get a reference to the panel s Graphics object and use that object s methods. The resulting graphics are drawn only on the panel. Getting a reference to a JPanel component s Graphics object is similar to previous examples. Instead of overriding the JPanel object s paint method, override its paintcomponent method. This is true for all Swing components except JApplet and JFrame. 2010 Pearson Addison-Wesley. All rights reserved. 14-43

Drawing on Panels The paintcomponent method serves the same purpose as the paint method. When it is called, the component s Graphics object is passed as an argument. public void paintcomponent(graphics g) When overriding this method, first call the base class s paintcomponent method. super.paintcomponent(g); 2010 Pearson Addison-Wesley. All rights reserved. 14-44

Drawing on Panels After this you can call any of the Graphics object s methods to draw on the component. Example: GraphicsWindow.java, DrawingPanel.java, GraphicsWindow.html 2010 Pearson Addison-Wesley. All rights reserved. 14-45

Checkpoint 3 14.18 to access the Graphics component in AWT, JApplet or JFrame, you must override while in JPanel, you must override 2010 Pearson Addison-Wesley. All rights reserved.

Checkpoint 3 14.18 to access the Graphics component in AWT, JApplet or JFrame, you must override paint while in JPanel, you must override paintcomponent repaint array of x and y values of each pt 2010 Pearson Addison-Wesley. All rights reserved.

Handling Mouse Events The mouse generates two types of events: mouse events and mouse motion events. Any component derived from the Component class can handle events generated by the mouse. To handle mouse events you create: a mouse listener class and/or a mouse motion listener class. 2010 Pearson Addison-Wesley. All rights reserved. 14-48

Handling Mouse Events A mouse listener class can respond to any of the follow events: The mouse button is pressed. The mouse button is released. The mouse button is clicked on (pressed, then released without moving the mouse). The mouse cursor enters a component s screen space. The mouse cursor exits a component s screen space. A mouse listener class must implement the MouseListener interface. 2010 Pearson Addison-Wesley. All rights reserved. 14-49

Mouse Listener Methods public void mousepressed(mouseevent e) called if the mouse button is pressed over the component. public void mouseclicked(mouseevent e) called if the mouse is pressed and released over the component without moving the mouse. public void mousereleased(mouseevent e) called when the mouse button is released. public void mouseentered(mouseevent e) called when the mouse cursor enters the screen area of the component. public void mouseexited(mouseevent e) This method is called when the mouse cursor leaves the screen area of the component. 2010 Pearson Addison-Wesley. All rights reserved. 14-50

Mouse Events The MouseEvent object contains data about the mouse event. getx and gety are two common methods of the MouseEvent class. They return the X and Y coordinates of the mouse cursor when the event occurs. Once a mouse listener class is created, it can be registered with a component using the addmouselistener method 2010 Pearson Addison-Wesley. All rights reserved. 14-51

Mouse Motion Events The appropriate methods in the mouse listener class are automatically called when their corresponding mouse events occur. A mouse motion listener class can respond to the following events: The mouse is dragged The mouse moved. A mouse motion listener class must implement the MouseMotionListener interface and it s methods. 2010 Pearson Addison-Wesley. All rights reserved. 14-52

Mouse Motion Listener Methods public void mousedragged(mouseevent e) called when a dragging operation begins over the component. The mousepressed method is always called just before this method. public void mousemoved(mouseevent e) called when the mouse cursor is over the component and it is moved. Example: MouseEvents.java MouseEvents.html 2010 Pearson Addison-Wesley. All rights reserved. 14-53

Using Adapter Classes The mouse listener class must implement all of the methods required by the interfaces they implement. If any of the methods are omitted, a compiler error results. The MouseAdapter and MouseMotionAdapter classes provide empty implementations of the methods. They can serve as base classes for mouse listener and mouse motion listener classes. Examples: DrawBoxes.java, DrawBoxes.html, DrawBoxes2.java, DrawBoxes2.html 2010 Pearson Addison-Wesley. All rights reserved. 14-54

Checkpoint 4 2010 Pearson Addison-Wesley. All rights reserved.

Checkpoint 4 mouse click is when mouse is pressed and released without moving mouseevent. getx and gety. 2010 Pearson Addison-Wesley. All rights reserved.

Timer Objects Timer objects automatically generate action events at regular time intervals. This is useful when you want a program to: perform an operation at certain times or after an amount of time has passed. Timer objects are created from the Timer class. The general format of the Timer class s constructor: Timer(int delay, ActionListener listener) 2010 Pearson Addison-Wesley. All rights reserved. 14-57

Timer Objects The delay parameter is the amount of time between action events in milliseconds. The the listener parameter is a reference to an action listener to be registered with the Timer object. Passing null will cause no action listener to be registered. the Timer object s addactionlistener method can register an action listener after the object s creation. 2010 Pearson Addison-Wesley. All rights reserved. 14-58

Timer Object Methods void addactionlistener (ActionListener listener) Registers the object referenced by listener as an action listener. int getdelay() Returns the current time delay in milliseconds. boolean isrunning() Returns true if the Timer object is running. void setdelay(int delay) Sets the time delay in milliseconds. void start() Starts the Timer object. void stop() Stops the Timer object. 2010 Pearson Addison-Wesley. All rights reserved. 14-59

Timer Object Methods An application can use a Timer object to automatically execute code at regular time intervals. Example: BouncingBall.java BouncingBall.html 2010 Pearson Addison-Wesley. All rights reserved. 14-60

Checkpoint 5 2010 Pearson Addison-Wesley. All rights reserved.

Checkpoint 5 ActionEvent in milliseconds 2010 Pearson Addison-Wesley. All rights reserved.

Playing Audio Java programs can play audio that is stored in a variety sound file formats..aif or.aiff (Macintosh Audio File).au (Sun Audio File).mid or.rmi (MIDI File).wav (Windows Wave File) One way to play an audio file is to use the Applet class s play method. One version of this method is: void play(url baselocation, String filename) 2010 Pearson Addison-Wesley. All rights reserved. 14-63

Playing Audio The argument passed to baselocation is a URL object that specifies the location of the file. The argument passed to filename is and name of the file. The sound that is recorded in the file is played one time. The getdocumentbase or getcodebase methods can get a URL object for the first argument. 2010 Pearson Addison-Wesley. All rights reserved. 14-64

Playing Audio The getdocumentbase method returns a URL object containing the location of the HTML file that invoked the applet. play(getdocumentbase(), "mysound.wav"); The getcodebase method returns a URL object containing the location of the applet s.class file. play(getcodebase(), "mysound.wav"); If the sound file specified by the arguments to the play method cannot be found, no sound will be played. 2010 Pearson Addison-Wesley. All rights reserved. 14-65

Using an AudioClip Object The Applet class s play method: loads a sound file, plays it one time, and releases it for garbage collection. If you need to load a sound file to be played multiple times, use an AudioClip object. An AudioClip object is an object that implements the AuidoClip interface. 2010 Pearson Addison-Wesley. All rights reserved. 14-66

Using an AudioClip Object The AudioClip interface specifies the following three methods: play plays a sound one time. loop repeatedly plays a sound. stop causes a sound to stop playing. The Applet class s getaudioclip method can be used to create an AudioClip object: AudioClip getaudioclip(url baselocation, String filename) The method returns an AudioClip object that can be used to play the sound file. Example: AudioDemo2.java, AudioDemo2.html 2010 Pearson Addison-Wesley. All rights reserved. 14-67

Playing Audio in an Application Playing audio in from a JFrame is slightly different than playing audio from an applet. // Create a file object for the step.wav file. File file = new File("step.wav"); // Get a URI object for the audio file. URI uri = file.touri(); // Get a URL for the audio file. URL url = uri.tourl(); Example: AudioFrame.java // Get an AudioClip object for the sound // file using the Applet class's static // newaudioclip method. sound = Applet.newAudioClip(url); 2010 Pearson Addison-Wesley. All rights reserved. 14-68

Checkpoint 6 2010 Pearson Addison-Wesley. All rights reserved.

Checkpoint 6 play play only loads a clip, plays it once, and removes it from RAM, AudioClip allows playing a clip several times or looping 2010 Pearson Addison-Wesley. All rights reserved.