by Debasis Samanta
From Chapter 1 to Chapter 8, we have learnt what we can do with Java. Truly speaking, we can do anything whatever we want. In the current Chapter, we are to explore how Java can do a lot even in the world of entertainment. Two main cooks for entertainment : Multimedia and Web page will be highlighted.
In broad sense, multimedia is the processing of audio, video, image/graphics, and text in such a way that one can create them, linked them, interact with them and all these things in a real time fashion. Processing of all these, although requires extra hardware support, and presently, number of professional tools are readily available in the market, but Java is unique because of its incomparable feature of portability.
In this Section, we will elaborate the basic multimedia objects that Java supports.
To play an audio data, it requires a specific format that the working platform can support. Java can play back audio data over a wide range of platforms. According to Java convention, all audio data should come from a URL ( Universal Resource Locator ) in a .au audio file. In order to use existing sounds in formats such as .wav or .aiff, one need to convert these to .au using a sound program that supports audio conversion. If one try to use .wav then Java is unable to support it and throws an InvalidAudioFormatException, which will not play the audio. The .au file refers to an 8-bit, 8Khz encoded audio file. This format doesn't represent the state of the art in audio fidelity, but is adequate for most sound clips.
There are two ways to play a sound file from an applet. The first way to play a sound is through the play() method and the other through the AudioClip of the Applet class object.
Using play() method :This method comes in two versions, both of which take a URL for a sound file, load the file into the memory, and then play the sound for one time. The play() method is as follows :
Following is the Illustration 9.1 to play a sound when a button is pressed.public void play (URL url ) - plays an audio clip if the audio clip referred to by the URL is found. public void play (URL url, String name) - same as the previous method, but uses a base URL and file name to locate the audio file.
Illustration 9.1 // Playing an audio clip // import java.applet.*; import java.awt.*; public class AudioPlayTest extends Applet { public void init ( ) { // To Place a Play button in the applet setLayout (new FlowLayout (FlowLayout. CENTER )); Button playButton = new Button ("Play" ); add (playButton ); } public boolean action (Event e, object button) { if ("Play".equals (button)) { play (getDocumentBase ( ), "audio\bell.au" ); return true; } } }
This applet simply plays the audio file bell.au which is located in the audio sub directory of the directory of the HTML file that loaded the applet. The audio file is cached in memory before playing it.
Note : URL actually a source of an object in Internet site. A typical URL which is actually having various component may look like as below :
Here, we have specified an audio file "music.au" which is available in the sub directory "audio" at the server node "sun".
There are two methods defined in Applet class, getDocumentBase() and getCodeBase() which are very useful to load data from the directory that had the HTML file that started the applet(document base), and the directory that the class file was loaded from (code base ). These two methods return a URL object.
Using Audio clip object :The disadvantage of using the play() method is that the first time you call it with a given audio file, it will have to down load the file if it hasn't been used before. This can happen responsiveness in cases like the previous example, where we want to play the sound in response to a user action, and the user ends up waiting for the sound to load in response to hitting a button. Also, the play() method is present only in the applet, which means that to use it from a component, or from within a thread, we need to have a reference to the applet. Last, the play() method plays a sound only once and must be called again if one wants to play the sound next.
The AudioClip object solves many of these limitations. To obtain an AudioClip object, one has to call the Applet's getAudioClip() method, which is defined as follows :
public AudioClip getAudioClip (URL url ) - returns an AudioClip object. This method will not return until the AudioClip has been loaded from the specified URL, so one should consider placing it in a separate thread if the file is expected to take a while to down load. public AudioClip getAudioClip (URL url, String name ) - same as the previous method, but finds the audio file using the base URL and file name. The AudioClip object specifies three methods which are stated below : public abstract void loop( ) - plays the clip in a continuous loop. public abstract void play( ) - starts playing the clip from its beginning. public abstract void stop( ) - stops the clip if it is currently playing. Here, audio played by the AudioClip() is asynchronous play that can be possible with the above three methods. Following is the Illustration 9.2 of an applet that plays a sound as long as the applet is on - screen or until the 'Stop' button is clicked :
Illustration 9.2 // Play audio through Audio clip // import java.applet.*; import java.awt.*; public class AudioClipTest extends Applet { AudioClip flute ; AudioClip piano ; public void init ( ) { // applet initialize setLayout (new FlowLayout (FlowLayout.CENTER )); Button testButton = new Button ( "Start" ); add(testButton); testButton = new Button( "Continue"); add(testButton); testButton = new Button ( "Stop"); add(testButton); flute = getAudioClip( getDocumentBase( ), "flute.au"); piano = getAudioClip( getDocumentBase( ), "piano.au"); } public void start( ) { // Continue the play of Piano piano.loop( ); } public void stop( ) { // Stop the Piano play piano.stop( ); } public boolean action( Event e, Object button) { if( "Start".equals(button) ) flute.play( ); if( "Continue".quals(button) ) piano.loop( ); if ( "Stop".equals(button) ) piano.stop( ); return true; } }
In the above illustration, applet loads two audio clips vide its init() method. First is "flute.au" and the second is "piano.au". The init() method will not finish until the sounds have been loaded. When the applet's start() is called, it starts the "piano.au". The thread of an event driven method action() is started, thus, if user hit "Start" button the "flute.au" audio clip will come into play. Note that, two audio clips will then come into play simultaneously. Thus, using AudioClip object multiple audio can be played, provided that the working platform supports multiple audio channel. The play will continue until the applet is closed.
Java is popular because it has the promise of creating rich graphical experiences. Java has a number of classes designed to deal with images and image manipulation. Java follows both JPEG (Joint Photographic Expert Group) and GIF (Graphics Interchange Format ) as the formats for image data. In general , JPEG images are better suited to natural color images such as photo graphs, and GIF images are best for graphical logos, rules, and button images.
These are basics, all of them defined in java.awt package, and many more also related to image manipulation.There are five types of objects that one will need to deal with or at least understand when dealing with Images. These are : Image ImageObserver ImageProducer ImageConsumer ImageFilter
Image class: With this class one can load an image object that obtains its pixel data from a specific URL. The most common way to do this is through the use of the getImage() method of the java.applet.Applet class, which has the following two forms :
Let us take a took at a very simple applet that loads and then draw an image (Illustration 9.3)public Image getImage (URL url ) - returns an Image object given a URL. public Image getImage (URL url, String name )- returns an Image object given a base URL and file name.
Illustration 9.3 // Draw an Image // import java.applet.*; import java.awt.*; public class ImageTest extends Applet { Image mona; public void init ( ) { mona = getImage (getDocumentBase ( ), "monalisa.gif "); } public void point (Graphics g ) { g.drawImage (mona, 0, 0, this); } }
In the above mentioned applet, first init() method loads the image object from the specified URL and file name. The paint() method uses drawImage() method ( it is defined in Component class); it has the form as below :
public abstract boolean drawImage ( Image imageName, int x, int y, ImageObserver imgObs );
imageName is the image reference that has to be drawn, the x, y coordinates to paint at, and imgObs is the ImageObserver that can monitors an image while it loads, we will learn more about it during the subsequent discussion. In the example Illustration 9.3, this represents the default ImageObserver. When this applet runs, it starts loading "monalisa.gif " in the init() method. On screen you can see the image as it loads from the Network ( or local machine), because the default ImageObserver interface calls paint() method every time more image data arrives from the source.
ImageObserver class :ImageObserver is an abstract interface used to get notification as an image is being generated. As we have seen in the last example, the drawImage() method takes both an Image object and an ImageObserver object. In the case of an ImageObserver object, because ImageObserver is an interface, we need to pass a reference to an instance of a class that implements the ImageObserver interface. Classes that implements the ImageObserver interface are required to have an imageUpdate() method as follows :
public abstract boolean imageUpdate (Image img, int status , int x, int y, int width, int height);Before going to know the use of this method in an applet, let us see about the various arguments in it :
Image img - the Image object references that has to be drawn on the applet.The use of the imageUpdate() method can be summarized as stated below :
int status - this gives us the status information of the image "img" being processed. The " status" integer is tested bit wise against the value of one or more flags. The available flags and the information they provide are listed in Table 9.1
int (x, y, width, height )- is a configuration for rectangle that reports different information about the image under loading.
When an Image object is referred, the imageUpdate() of this object will call repaint() method which will cause the paint() method to eventually call again. The drawImage() is thus again called, and it again draws all the pixel data it has loaded so far, which at this point should be more than had been loaded the last time drawImage() was called. The partial image is again drawn, and this time, because more pixel data has been loaded, more of the image is drawn and appears on the screen. When more pixel data is loaded, imageUpdate() is again called, and the cycle repeats itself, until all the pixel data has been loaded and the complete image has been drawn.
Table 9.1
Bits |
Indicator |
WIDTH |
The width of the base image is now available and can be taken from the width argument. |
HEIGHT |
The height of the base image is now available and can be taken from the height argument |
PROPERTIES |
The properties of the image are now available. One can access the properties with img.properties. |
SOMEBITS |
More pixels needed for drawing a scaled variation of the image are available. The bounding box of the new pixels can be taken from the x, y, width, and height argu ments. |
FRAMEBITS |
Another complete frame of a multiple frame image, which was previously drawn, is now available to be redrawn. The x, y, height, and width arguments should be ignored. |
ALLBITS |
The image being drawn is now complete and can be drawn again in its final form. The x , y, width, and height arguments are no longer meaningful. |
ERROR |
An image that was being tracked has encountered an error. No further image informa tion will be available and drawing the image will fail. |
ABORT |
An image that was being tracked was aborted before production was complete. No more image information will become available. |
Now let us look at an example that uses ImageObserver to see how many scan lines of the image have been processed and then prints the progress to the console.
Illustration 9.4 // Use of ImageObserver // import java.applet.*; import java.awt.*; import java.awt. image.*; public class ImageLoadTest extends Applet implement ImageObserver { image mona; Dimension d; int progress; boolean loaded; public void init ( ) { mona = getImage ( getDocumentBase ( ), "monalisa.gif " ); loaded = false; progress = 0; } public void paint (Graphics g ) { d = this.size; loaded = g.drawImage (mona, 0, 0, this ); } public boolean imageUpdate (Image img, int info, int x, int y, int width, int height ) { if (( info & ALLBITS ) != 1) { if (progress < d.height ) progress = progress + height; System.out.println( progress + "/" + d.height); return true; } else { return false; } } public void start( ) { mover = new Thread (this); mover.start( ); } public void stop( ) { mover.stop( ); } public void run( ) { mover.setPriority (Thread.MIN_PRIORITY); while (!loaded ) { repaint( ); try mover.sleep( 200 ); catch (Exception e); } } }
This applet, loads an image just as in Illustration 9.3. The difference in this example is that we are implementing our own imageUpdate() method over the default one. The imageUpdate() method processes the status of the image load. A summary of the status is passed in through info, against which the static variable ALLBITS is tested. If we have not yet received all of the bits in our image, we add the height value to the total number of scan line processed which will be printed to the system console. The run() method repaints the applet five times a second (every 200 milliseconds) while the image "mona" is not loaded. How long the status monitor will run depends on how quickly the Network connection can deliver the image date.
ImageProducer class :ImageProducer is an abstract interface for objects that want to produce data for Images. An object that implements the ImageProducer interface will supply integer or byte arrays that represent image data. The createImage() method (will be discussed shortly ) takes an ImageProducer object and returns an Image object.
We will examine a valuable class called MemoryImageSource that implements ImageProducer. We will create a new Image object from data generated by this producer.
MemoryImageSource : It is a class used to create a new Image from an array of pixels. Here is a constructor used to create a MemoryImageSource object :
public ImageProducer MemoryImageSource (int width, int height, int pixel[ ],int offset, int scan linewidth);The MemoryImageSource object is constructed out of an array of integers pixel[ ], in the default RGB color model to produce data for an image object. The constructor for MemoryImageSource also takes the width and height of the result, the offset into the pixel array, and the width of a scan line, This constructor returns an ImageProducer object which is used with createImage() to result in a usable image. Following is an illustration of ImageProducer.
Illustration 9.5 // Image Production // Import java.applet.*; import java.awt.*; import java.awt.image.*; public class MemoryImageProduce extends Applet { Image art; Dimension d; public void init ( ) { generateImage ( ); } public void generateImage ( ) { int pixels[ ] = new int [ d.width * d.height ]; int i = 0; int r, g, b; for (int y = 0 ; y < d.height; y++ ) { // Create a set of pixels for (int x = 0, x < d.width; x++ ) { r = (x ^ y ) & 0xff; g = ( x * 2 ^ y * 2 ) & 0xff ; b = ( x* 4 ^ y * 4 ) 0xff ; pixels [ i++ ] = (255< 24 ) | (r < 16 ) | (g < 8) | b; } } art = createImage( new MemoryImageSource( d.width, pixels, 0, d.width )); } public void paint( Graphics g ) g.drawImage (art, 0, 0, this )); } }
Here, the data for the new MemoryImageSource is created in the generateImage() method. An array of integers is created to hold pixel values; Then integer array elements get shifted into a pixel in the pixel array. Finally, we call createImage() to create a new Image from the 'pixels' array with MemoryImageSource.
There are many more about image handling : OffScreen, MediaTracker, ImageFilter, ImageFilterSource, CropImageFilter, RGBImageFilter etc. which are not possible to discuss in this Tutorial.
Web is a short form of very big concept World Wide Web, also nicknamed as WWW. Today, the most likely place you will find Java is on the web. The web act as a convenient transport mechanism for Java programs, and the web's ubiquity has popularized Java as an Internet development tool. In fact, Java dynamically extends the capability of web media. In this Section we are to explore how Java can support web.
What is web? The web is a huge collection of interconnected hypertext document on the Internet. A hypertext document is a document which contains hot links (on line) to other documents. Hypertext links are usually visible as highlighted (colored/underlined) word(s) in the text, but they can also be graphics, and are frequently used for on line help systems. Links are activated by clicking on them with a mouse.
The web is based on two standards : the HTTP protocol and the HTML language : HTTP for Hyper Text Transmission Protocol, and it describes the way that hypertext documents are transferred over the Internet. HTML is the abbreviation for Hyper Text Markup Language, and it specifies the layout and linking commands present in the hypertext document themselves.
The HTTP protocol is implemented in software on the server and the users machine (client). The server software is called a web server or HTTP server, and the client software is called a web browser. To open an HTML document, the web browser sends an HTTP commands to the sever requesting the document by its location (called URL, Universal Resource Location). The web server responds by sending the HTML document to the client. The client then displays the document on the user's screen. The HTML documents, again, not only contain text, it also may contain multimedia objects like graphics, audio, animation etc. which are generally stored in files and in the server's sub directory where the HTML document itself is located. Location of the resources on the web are specified with a URL. A URL specifies the protocol used to fetch a document as well as its location. This is already discussed in Chapter, Part II of this book.
To achieve all these, web developers have to face number of hurdles. Important among various difficulties is the platform independency i.e. it should present information in a way that can be viewed on almost every type of machine and operating system. It does not matter whether the environment is Pentium, or Macintosh, Windows 95 or UNIX.
Java shorted out this platform independency problem easily. Java addresses this problem by using Java applets. An applet is a Java program which appears embedded in a web document. The Java applets runs when it is loaded by a Java enabled web browser like HotJava, Netscape Navigator or Internet Explorer. The running applet then draws itself in the user's browser window according to the programmer's instructions. The applet can create its own network connections and use whatever protocol is required to get information from the server.
The next section, is devoted how to prepare a web documents in Java.
Java web pages are nothing but the HTML documents. Or in other words, an HTML document hosts number of applets to constitute a web page. In Section 2.2 of Chapter 2, Part II of this book, we have seen that an applet can not run independently unless it is embedded in a HTML document.
In this section, we are to discuss what are the basic elements to compose a HTML document and then how applet(s) can be embedded in it.
HTML files are text files with special character sequences that specify the document formatting characteristics. The special character sequences are called tags, and they consist of words placed between left and right angular brackets like
What are the various useful tags available for composing in HTML documents is discussed in Section 9.2.4 of the current Chapter.
For better understanding of full HTML, the reader may refer to a good HTML text entitled "The HTML Sourcs book" published by Ian Grahams, John Wiley Computer Publishing.
Following is an example, illustrating the basic formats of an HTML document
This file should be saved with a suitable file name and having extension .html. In the Illustration 9.6(a) the tag HTML indicates that the file is an HTML document, the HEAD tag marks the start of an header section that is normally used for recording the title and author of the document; the phrase between < TITLE> and TITLE> tags is the name of this document. Anything within the < TITLE> tags will not be displayed when the web page is run. The phrases between < BODY> and BODY> of the document are to compose the actual web page.
One can include an image (or audio etc.) file in an HTML file; an another HTML file can also be included. Following is an example taking these into consideration as given below :
In the Illustration 9.6 (b), an image file "monalisa.gif " is included in the HTML document with the IMG tag. This file will be down loaded by the browser from the directory in which these HTML file will be located ( or any directory as the sub directory of the directory the HTML file is in. One can specify other location than the such default location, (in that case full URL has to be specified). As an example, next IMG tag is having a source "www. nerist. in /etc/emblem.gif" which means that the image file is emblem.gif is in the directory /etc of the server www.nerist.in. Also, one can connect an HTML page to another document via a hypertext link. To do this one must insert an anchor tag ( < A>). A text between the anchor tag and the closing anchor tag will be highlighted, so the user knows that the highlighted text (or graphics) can be clicked on. In the current example a part of the page will appear as :
This highlighted text may appear in blue color and underlined - so that if user click here, then jump to the document info.html which is in the NERIST's server. One can insert < BR> and < P> etc. to break for a new line and a new paragraph. This may require because, a web browser ignores excess spaces and new lines when displaying a document.
Next we will see how applet(s) can be embedded within an HTML document.
The < APPLET> tag is used to start an applet from both an HTML document and from the JDK appletviewer. The appletviewer will execute each applet tag that it finds in a separate window, while web browser like HotJava, Netscape Navigator, and Internet Explorer will allow many applets on a single page.
Following is the Illustration 9.7 which includes an applet to run HellowJavaApplet :
In the last example, the applet is included with < APPLET> tag in a minimum way. There is much more, that one can specify with this tag. The detail syntax for the < APPLET> tag is given below :
The various attributes indicate the options that can be used when placing an applet on a web page. Many of these options are optional which are marked within square brackets.
The meaning of attributes are summarized as below :
CODE BASE = codebaseURL:
CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for the applet's executable class file (specified with the CODE tag). The HTML document's URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does not have to be on the host that the HTML document was read from.
CODE = appletFileName:
CODE is a required attribute that gives the name of the class file that contains your applet's compiled code (of applet ). This file is relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory indicated any CODEBASE, if set.
ALT = alternateText:
The ALT tag is an optional attribute which specifies a short text message that should be displayed if the browser understands the APPLET tag but can't currently run Java applets. This is distinct from the alternate HTML you provide for browsers that don't support applets.
NAME = appletInstanceName:
NAME is an optional attribute used to specify a name for the applet instance, applet must be named for other applets or the same page to find them by name and communicate. For example, to get an Applet subclass MyApplet named Twinkle use :
WIDTH= Pixels HEIGHT = Pixels:
WIDTH and HEIGHT are required attributes that give the initial size (in pixels ) of the applet display area.
ALIGN = alignment :
ALIGN is an optional attribute that specifies the alignment of the applet. This many have the possible values : LEFT, RIGHT, TOP, TEXTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM, ABSBOTTOM. LEFT is the default alignment.
VSPACE = pixels HSPACE= pixels:
These attributes optionally specify the space in pixels above and below the applet, VSPACE, and each side of the applet, HSPACE.
PARAM NAME = attributeName1 VALUE= attributeValue:
The PARAM tag is how one can pass applet-specific arguments in from attributes with the getParameter() method, which is illustrated as in Illustration 9.8.
If some parameter value is not specified in HTML's PARAMs but is referred in applet then the getParameter() will return a null.
Following Table 9.2 summarizes the basic HTML tags which are frequently in use to develop a web document.
Table 9.2
PARAGRAPH
FORMATTING <H1>...... </H1> Heading Level 1 (similarly <H2>
to <H6>) <H4> is normal text. <P ALIGN = = “alignment” ..... </P> Paragraph
break, alignment
can take one of the values- Left, Right or Center. <BR> Break a line <UL> ..... </UL> Unordered or Bulleted List. <OL> ...... </OL> Ordered or Numbered List. <L1> An item in a list. <CENTER> ...</CENTER> Center align anything enclosed in tags. <HR SIZE =x WIDTH=y> Horizontal
ruler line; x = number of pixels for thickness; y = number or
percentage for length. CHARACTER
FORMATTING <B> .... </B> Bold text. <I> ..... </I> Italicized text. <U> ...... </U> Underlined text <BLINK> ...</BLINK> Blinking text. <SUP> ..... </SUP> Superscript text <SUB> ..... </SUB> Subscript text. <TT> ...... <TT> Typewriter-like monospaced text <FONT SIZE=x FACE = “Typeface”
COLOR
=”color”> Font
enhancements: X can be a can start from 1-7 (1 being smallest) or
relative specification like -1, -2, +1 etc; typeface
is font name; color
is either color name or color code in hex number. <PRE> ....</PRE> Pre-formatted text (retains alignment and displays
text just as typed in. <COMMENT> ..... </COMMENT> This
is a comment line which is ignored by the browser. < !-COMMENT TEXT > This
is also a comment line which is ignored by the browser.
OTHER
TAGS <BODY BGCOLOR=color BACKGROUND
=”image”> Body
tag which controls general color and background settings; color
is hex RGB or name as background color; image
is location of background GIF/JPEG image file. <A HREF = “URL”> ....</A> Anchor tag to create a hypertext
reference/ link. URL
is the location of the external document/image etc. <A NAME = “name”> .... <A/> Anchor
tag to create an internal jump to a particular line of the page;
name is what the spot is called. <A HREF = “#name” > .....
</A> Create
a link to jump internally to a line of the page; name
is the spot which was created by the previous command. <IMG SRC = “file” ALIGN =
alignment ALT = “text”
HEIGHT=xWIDTH=Y> Add
images in GIF/JPEG format; file
is the name of the file to display; alignment
= left, right or centre aligns image with text word wrap, or else
alignment
= top, middle or bottom aligns subsequent text to top, middle or
bottom respectively; alt specifies alternative text if image is
not displyed; x
is height of image in pixels and y
is width of image.
Special Characters :
Special characters which are used in HTML document to control web pages are liste as in Table 9.3.
Table 9.3
Description Numerical
Code Character
Code Entity Non-breating
space     Copyright © © Registered
trademark ® ® Quotation
mark " " “ Ampersand & & & Less-than
sign < < < Greater
than sign > > > Soft
hyphen ­ ­ -
URL:
The URL for a web page that can be specified is as per the syntax given below :
For more information regarding the HTML document preparation, one may consult the following :
Abeginners's guide to HTML : WWW.ncsa.uiuc.edu/General/Internet/WWWW/HTMLPrimer.html
This is last but not least. Java is a collection of huge concepts and day-by-day Java features are upgrading, even when you are going through this Tutorial, lot of improvements might have been achieved. To know the latest stock of Java , you are advised to set contact http:// java. sun.com
Illustration 9.6 (a) // Basic format of an HTML document //
< HTML>
< HEAD>
< TITLE> A sample HTML demonstration < / TITLE>
< / HEAD>
< BODY>
< H1> HTML Demo H1>
Here is a simple normal text
< B> Here is some Bold text B>
< I> Here is some text in Italic I>
< / BODY>
< / HTML>
Illustration 9.6 (b) // Hyper text document //
< HTML>
< HEAD>
< TITLE> A hypertext Demo < / TITLE>
HEAD>
< BODY>
< IMG SRC= "monalisa.gif" >
< B> Following is another image from NERIST server B>
< IMG SRC = " http: // www. nerist.in /etc/ emblem.gif" >
Get the information of NERIST < BR>
< A HREF = "http : // www. nerist in /etc/ info.html">
NERIST Information < / A>
< / BODY>
< / HTML>
Applet hosted HTML Document
Illustrate 9.7 // A web page with an applet //
< HTML >
< HEAD>
< TITLE > An HTML Containing HelloJavaApplet < / TITLE>
< / HEAD>
< BODY>
< HI> Very simple web page Demo < / HI>
< APPLET CODE = " HelloJavaApplet.class">
WIDTH = 200 HEIGHT = 100 >< / APPLET>
< / BODY>
< / HTML>
Syntax for the < APPLET> Tag
< APPLET
[CODE BASE = codeBaseURL]
CODE = appletFileName
[ALT = alternateText]
[ NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALLIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels ]
>
[< PARAM NAME = attributeName1 VALUE = attributeValue>]
[< PARAM NAME = attributeName2 VALUE = attributeValue>]
[altermateHTML]
< / APPLET>
MyApplet appletInstanceName = getAppletContext ( ).getApplet ("Twinkle" );
Once you have the named instance, you can call methods on it as you would any object.
Illustration 9.8 // Passing parameter from and to APPLET HTML //
< HTML>
.
.
< APPLET CODE = ParamTest WIDTH = 40 HEIGHT = 40>
< PARAM NAME = fontName VALUE = Universe>
< PARAM NAME = fontSize VALUE =14>
< PARAM NAME = leading VALUE=2>
.
.
HTML>
Here is how one would extract each parameter from the applet :
.
.
// In an applet
String font = getParameter (" fontName" );
int sizeFont = Integer.parseInt (getParameter ( " fontSize" ));
float leading = float.valueof (getParameter ( "leading" ));
.
.
HTML Snapshots
Some Color Codes:
In web document one can use color codes to manage various colors. These are listed as below :
Aqua #00FFF Black #00000 Blue #0000FF Fuchsia #FF00FF
Brown #A52924 Cyan #00FFF Darkblue #000088 Orange #FFA500
Gray #808080 Green #008000 Lime #00FF00 Maroon #80000
Navy #000080 Olive # 808000 Purple #800080 Red #FF0000
Silver #C0C000 Teal #009080 White #FFFFF Yellow #FFFF00
Service: //hostname/directory(and/or filename)
Service can be:
HTTP - Hypertext transfer protocol for web pages
FTP - File Transfer Protocol
Practice Questions
Practice 9.1
Below, is a "complete" program. It draws 10 randomly placed lines of randomly selected colors on the image at a time; in a separate thread, it then displays the "updated" image. The drawing is done in the paint method, and the display is done in the run method. Other applications that used this architecture would move an object across the screen in the paint method one increment at a time, display one of a list of images for an animation, etc.
import java.applet.*;
import java.awt.*;
import java.util.*;
public class DoubleBuf extends Applet implements Runnable {
boolean pause = false;
Thread runThread = null;
Image offScreen;
int rd, gr, bl;
int x1, y1, x2, y2;
Color c;
Color backGround = new Color (0xffffff);
int imageWidth, imageHeight;
Random random;
// ************* init
public void init () {
random = new Random ();
} // end init
// ************* start
public void start () {
runThread = new Thread ( this );
runThread.start ();
} // end start
// ************* stop
public void stop () {
if ( runThread != null ) runThread.stop ();
runThread = null;
} // end stop
// ************* mouseDown
public boolean mouseDown ( Event event, int x, int y) {
if ( runThread != null ) pause = true;
else {
pause = false;
start ();
} // end else;
return true;
} // end stop
// ************* paint
public void paint ( Graphics g, Dimension d ) {
for ( int i = 0; i < 10; i++ ) {
rd = (int)( 255 * random.nextFloat () );
gr = (int)( 255 * random.nextFloat () );
bl = (int)( 255 * random.nextFloat () );
x1 = (int)( d.width * random.nextFloat () );
y1 = (int)( d.height * random.nextFloat () );
x2 = (int)( d.width * random.nextFloat () );
y2 = (int)( d.height * random.nextFloat () );
g.setColor ( new Color ( rd, gr, bl ) );
g.drawLine ( x1, y1, x2, y2 );
} // end for
} // end paint
// ************* run thread
public void run () {
Dimension d;
Graphics g;
while ( ! pause ) {
d = this.size ();
if ( ( offScreen == null ) ||
( imageWidth != d.width ) ||
( imageHeight != d.height ) ) {
offScreen = this.createImage ( d.width, d.height );
imageWidth = d.width;
imageHeight = d.height;
} // end if
g = offScreen.getGraphics ();
paint ( g, d );
g = this.getGraphics ();
g.drawImage ( offScreen, 0, 0, Color.white, this );
try {Thread.sleep ( 10 );} catch ( InterruptedException e) {;}
} // end while
runThread = null;
} // end run
} // end DoubleBuf
Practice 9.2
//This will play an .au file:
import java.io.InputStream;
import java.net.*;
import java.applet.*;
import java.awt.Graphics;
import java.awt.Color;
public class Message extends java.applet.Applet {
private String file;
private AudioClip source;
public void init() {
setBackground(new Color(0));
file=getParameter("FILE");
source=getAudioClip(getDocumentBase(),file);
}
public void start() {
if(source!=null) source.play();
}
public void stop() {
if(source!=null) source.stop();
}
}
Practice 9.3
The key objects and methods used are AudioClip, loop() and stop(). Another method not used here but perhaps of some value is the play() method which plays an audio clip one time.
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
public class PlayAudio extends Applet
{
AudioClip myAudio;
Button b_play;
Button b_stop;
String textString;
public void init()
{
resize(300, 100);
b_play = new Button("Play audio");
b_stop = new Button("Stop audio");
myAudio = getAudioClip(getDocumentBase(), "computer.au");
add(b_play);
add(b_stop);
}
public void start()
{
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawString(textString, 100,75);
}
public boolean action(Event e, Object arg)
{
if(e.target instanceof Button)
{
if("Play audio" == arg)
{
myAudio.loop();
textString = "Playing audio...";
}
if("Stop audio" == arg)
{
myAudio.stop();
textString = "Not playing audio...";
}
}
repaint();
return true;
}
}
Practice 9.4
// load an Image into a standalone Java application panel (i.e. one that does not have a base URL
import java.awt.*;
import java.awt.image.*;
public class ImageWindow extends Frame
{
Image im=null;
public ImageWindow()
{
}
public void createImage()
{
im = getToolkit().getImage("b01.gif");
}
public void paint(Graphics g)
{
update(g);
}
public void update(Graphics g)
{
g.drawImage(im, 0, 0, this);
}
public boolean handleEvent(Event evt)
{
if (evt.id == Event.WINDOW_DESTROY)
{
System.exit(0);
}
return super.handleEvent(evt);
}
public static void main(String args[])
{
ImageWindow window = new ImageWindow();
window.createImage();
window.setTitle("Java StandAlone Application");
window.pack();
window.resize(500,300);
window.show();
}
}
Assignment
Design JPanel the plays media from a URL.Test simple media player .
Q&A
What is multimedia?
Multimedia is a technique that incorporates
text,
graphics,
sound,
animations and
video elements.
Mention some of the image formats used in multimedia?
Some of the image formats used in multimedia are
GIF files
JPG files
Animated GIF files
MPEG files
Shockwave files and
Nx View files.
What Is Lossless Source Coding?
Lossless source coding is one of the data compression standards.
Images, audio and video files use lossless source compression standard.
Lossless source encoding is suitable for compressing text files.