Introduction Executing an applet Applet class Applet tags and attributes Enabling Applets to run as Application Multimedia Applet context Chapter 2 Applets and Multimedia 1. Introduction Applets Java programs that can be embedded in HyperText Markup Language (HTML) documents // WelcomeApplet.java: Applet for displaying a message import javax.swing.*; public class WelcomeApplet extends JApplet { /** Initialize the applet */ public void init() { add(new JLabel("Welcome to Java", JLabel.CENTER)); } } <html> <head> <title>Welcome Java Applet</title> </head> <body> <applet code = "WelcomeApplet.class width = 350 height = 200> </applet> </body> </html>
Introduction (cont) // WelcomeApplet.java: Applet for displaying a message import javax.swing.*; public class WelcomeApplet extends JApplet { /** Initialize the applet */ public WelcomeApplet() { add(new JLabel("Welcome to Java", JLabel.CENTER)); } } // WelcomeApplet.java: Applet for displaying a message import javax.swing.*; public class WelcomeApplet extends JApplet { /** Initialize the applet */ public void init() { add(new JLabel("Welcome to Java", JLabel.CENTER)); } } Alternative coding 2. Executing an Applet 2 ways: Appletviewer Web browser WelcomeApplet Run Applet Viewer 2.1 Executing an Applet using Appletviewer Using appletviewer In the directory containing the applet and HTML document, type appletviewer <html file> The appletviewer understands only the <applet> and </applet> HTML tags and ignores all other tags
2.2 Executing an Applet in a Web Browser To execute an applet in Internet Explorer: Select Open from the File menu Click the Browse button Locate the directory containing the HTML document for the applet you wish to execute Select the HTML document Click the Open button Click the OK button 3. The Applet Class Figure illustrating the Applet inheritance hierarchy Object Component Panel Applet JApplet Container Window Frame JFrame Every applet is a subclass of java.applet.Applet. The Applet Class public class MyApplet extends java.applet.Applet { ... /** The no-arg constructor is called by the browser when the Web page containing this applet is initially loaded, or reloaded */ public MyApplet() { ... } public void init() { ... } public void start() { ... } public void stop() { ... } public void destroy() { ... } /** Other methods if necessary. Eg paint() */ } Reload enter Web Page init() stop() destroy() start() After init Return to page Go to another page Exits The Applet Class(cont) When the applet is loaded, the Web browser creates an instance of the applet by invoking the applets no-arg constructor. The browser uses the init, start, stop, and destroy methods to control the applet. By default, these methods do nothing. To perform specific functions, they NEED to be modified in the user's applet so that the browser can call your code properly. The init() Method Invoked when the applet is first loaded and again IF the applet is reloaded. Normally performs functions loading images, setting up user-interface components The start() Method Is called whenever the user returns to the page containing the applet after surfing other Web pages. Contains any operation that needs to be performed whenever the Web page containing the applet is visited. Example An applet with animation might use the start method to resume animation. Paint() Called after methods init and start Is also called when the applets needs to be repainted Generally used in drawing a graphic object passed to the method.
The stop() Method The stop() method is invoked when the user moves off the page. Use this to stop animation, audio files The destroy() Method Invoked by the browser to inform the applet that it is no longer needed. Use this method to release any resources it has allocated. Usually, there is no need to write this method. The JApplet Class The Applet class is an AWT class and is not designed to work with Swing components. To use Swing components in Java applets, it is necessary to create a Java applet that extends javax.swing.JApplet, which is a subclass of java.applet.Applet. JApplet inherits all the methods from the Applet class. In addition, it provides support for laying out Swing components. Example import java.awt.*; import javax.swing; public class BasicEventApplet extends JApplet { JTextArea messages = new JTextArea(8, 30); public BasicEventApplet() { messages.append( "Constructor\n" ); } public void init() { add( messages ); messages.append( "Init\n" ); } public void start() { messages.append( "Start\n" ); } public void stop() { messages.append( "Stop\n" ); } public void destroy() { messages.append( "Destroy\n" ); } public void paint( Graphics g ) {messages.append( "Paint\n" ); } } Example: Using Applets Objective: Compute Loans. The applet enables the user to enter the annual interest rate, the number of years, and the loan amount. Click the Compute Loan button, and the applet displays the monthly payment and the total payment. Run Applet Viewer LoanApplet 4. Applet Tag and Attributes <applet code=classfilename.class width=applet_viewing_width_in_pixels height=applet_viewing_height_in_pixels [archive=archivefile] [codebase=applet_url] [vspace=vertical_margin] [hspace=horizontal_margin] [align=applet_alignment] [alt=alternative_text] <param name=param_name1 value=param_value1> </applet> Use alt display alternative text on browsers that do not support applets. The tag below provides such text.
Example <applet code="BasicEventApplet.class" width=300 height=200 alt= Your browser does <B>not</B> support applets! So you can not use my great applet. </APPLET>
Codebase: location of the class file relative to the web page Eg: <applet code=welcome.class width=100 height=150 codebase=myApplets>
Archive:list of Java archive file(s) containing the classes and other resources for the applet. These files are fetched from web server before the applet is loaded. Eg:<applet code=calculator.class width=100 height=150 archive=calculatorclasses.jar >
hspace and vspace control horizontal and vertical spacing around the applet.
Applet Tag and Attributes (cont) Passing Parameters to Applets <applet code = "DisplayMessage.class" width = 200 height = 50> <param name=FONT value=Helvatica"> <param name=SIZE value=24> alt="You must have a Java-enabled browser to view the applet" </applet> public class DisplayMessage extends Japplet { public void init() { string fontName = getParameter(FONT); int fontSize = integer.parseInt(getParameter(SIZE));
} } Pass information to an applet from the html page. getParameter() method will read arguments with the param tag. Example: Passing Parameters to Java Applets Objective: Display a message at a specified location. The message and the location (x, y) are obtained from the HTML source. Run Applet Viewer DisplayMessage DisplayMessage html file.txt 5. Conversions Between Applications and Applets Applets have security restrictions Applets are not allowed to read from, or write to, the file system of the computer viewing the applets. Applets are not allowed to run any programs on the browsers computer. Applets are not allowed to establish connections between the users computer and another computer except with the server where the applets are stored.
Conversions Between Applications and Applets (cont) Conversions between applications and applets are simple and easy. You can convert an application to an applet as long as security restrictions are not violated. You can always convert an applet into an application. Add a main method in the applet.
public static void main(String[] args) { JFrame frame = new JFrame("Applet is in the frame"); MyApplet applet = new MyApplet(); frame.add(applet, BorderLayout.CENTER); applet.init(); applet.start(); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } Conversions Between Applications and Applets (cont) Example: Running a Program as an Applet and as an Application Objective: Modify MessageApplet to enable it to run both as an applet and as an application. Run as Application Run as Applet DisplayMessageApp 6. Multimedia URLs Obtaining multimedia files Images Audio clips
6.1 Locating Resource Using the URL Class The java.net.URL class can be used to identify files (image, audio, text, etc.) on the Internet. Eg : URL u=new URL(http//java/sun.com/index,html);
Locating Resource Using the URL Class(cont) An URL for a file can also be accessed by class code if the file is located in the class directory. The class directory is where the class (i.e., the .class file) is stored.
Eg. suppose the class directory is c:\book, the following statements create a URL for c:\book\image\us.gif.
Class class = this.getClass(); URL url = class.getResource("image/us.gif"); ImageIcon imageIcon=new ImageIcon(url);
Example Write a program that displays an image from /image/us.gif in the class directory on a panel. Run DisplayImageWithURL Applet methods: getCodeBase method gets URL of the applet code getDocumentBase method gets the URL of the HTML page that contains the applet.
Locating Resource Using the URL Class(cont) 6.2 Loading and Displaying Images Java supports several image formats, including GIF, JPEG and PNG Classes for loading and displaying images Image ImageIcon Image objects Applet method getImage loads an Image into an applet Use Graphics method drawImage to scale and draw image ImageIcon objects Use paintIcon to draw image
1 // Fig. 21.1: LoadImageAndScale.java 2 // Load an image and display it in its original size and twice its 3 // original size. Load and display the same image as an ImageIcon. 4 import java.awt.Graphics; 5 import java.awt.Image; 6 import javax.swing.ImageIcon; 7 import javax.swing.JApplet; 8 9 public class LoadImageAndScale extends JApplet 10 { 11 private Image image1; // create Image object 12 private ImageIcon image2; // create ImageIcon object 13 14 // load image when applet is loaded 15 public void init() 16 { 17 image1 = getImage( getDocumentBase(), "redflowers.png" ); 18 image2 = new ImageIcon( "yellowflowers.png" ); 19 } // end method init 20 21 // display image 22 public void paint( Graphics g ) 23 { 24 super.paint( g ); 25 26 g.drawImage( image1, 0, 0, this ); // draw original image 27 28 // draw image to fit the width and the height less 120 pixels 29 g.drawImage( image1, 0, 120, getWidth(), getHeight() - 120, this ); 30
31 // draw icon using its paintIcon method 32 image2.paintIcon( this, g, 180, 0 ); 33 } // end method paint 34 } // end class LoadImageAndScale
Applet methods getAudioClip(URL) getAudioClip(URL, String) newAudioClip(url); Return an object that implements the AudioClip interface. play(URL) play(URL, String) Play the AudioClip corresponding to the specified URL. The AudioClip interface defines the following methods: loop Starts playing the clip repeatedly. play Plays the clip once. Each time when this method is called, the clip is restarted from the beginning stop Stops the clip. Works with both looping and one-time sounds.
6.3 Loading and Playing AudioClip Loading and Playing AudioClip (cont) Eg 1 Class class = this.getClass(); URL url = class.getResource("beep.au"); AudioClip audioClip = Applet.newAudioClip(url);
Eg2 AudioClip onceClip, loopClip; onceClip = applet.getAudioClip(getCodeBase(), "bark.au"); loopClip = applet.getAudioClip(getCodeBase(), "train.au"); onceClip.play(); //Play it once. loopClip.loop(); //Start the sound loop. loopClip.stop(); //Stop the sound loop. Example : Playing Audio Run DisplayImagePlayAudio The AppletContext provides the ability for the applet to ask the browser to perform tasks for the applet.
Note: getAudioClip(), getImage(), showStatus() in the Applet class call the corresponding methods in the AppletContext.
7. The Applet Context All browsers allow applets to display a short status string public void showStatus(String status) Requests that the argument string be displayed in the status bar of the browser or the appletviewer. Eg Image image = getImage(getCodeBase(), "imgDir/a.gif"); . g.drawImage(image, 0, 0 this); showStatus("MyApplet: Loading image file "); The AppletContext - showStatus public void showDocument(URL url) Replaces the Web page currently being viewed with the given URL. public void showDocument(URL url, String target) Requests that the browser or applet viewer show the Web page indicated by the url argument. The target argument indicates in which HTML frame the document is to be displayed.
The AppletContext - showDocument
Target Meaning
"_self" Show in the window and frame that contain the applet
"_parent" Show in the parent frame. If the applet's frame has no parent, acts the same as "_self"
"_top" Show in the topmost frame of the applet's window. If the applet's frame is the top-level, acts the same as "_self"
"_blank" Show in a new unnamed top-level window.
Name Show in the frame or window named name. If name does not exist,create a new top-level window named name, and show the document in it
The AppletContext - showDocument
import java.applet.*; Import javax.swing; import java.net.URL; import java.net.MalformedURLException; public class ShowDocumentApplet extends JApplet { public void init( ) { try { URL wwwSun = new URL( "http://java.sun.com/" ); AppletContext myContext = getAppletContext(); myContext.showDocument( wwwSun, "_blank"); } catch (MalformedURLException punt ) { } } }