Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP201 Java Programming Part II: GUI Programming Topic 11: Applets Chapter 10.

Similar presentations


Presentation on theme: "COMP201 Java Programming Part II: GUI Programming Topic 11: Applets Chapter 10."— Presentation transcript:

1 COMP201 Java Programming Part II: GUI Programming Topic 11: Applets Chapter 10

2 COMP201 Topic 11 / Slide 2 Outline l Introduction l What are applets? l How to run? l Applets basics l Class loader and JAR files l Security basics l Applet life cycle l Converting applications to applets l Resources for applets l Communication with browser

3 COMP201 Topic 11 / Slide 3 Introduction l So far, we’ve only covered topics related to stand-alone applications l An applet is designed to run within a browser l Bring web pages to life l Reason behind hype in Java Note: Java is not a language for designing web pages. It is a tool for bring them to life.

4 COMP201 Topic 11 / Slide 4 Introduction / JApplet Class An applet is a Java class which extends java.applet.Applet If Swing components are used, the applet must extend from javax.swing.JApplet We will only discuss applets that extend JApplet JApplet is a sub-class of Applet, which in turn is a subclass of Panel l Event handling exactly the same as before

5 COMP201 Topic 11 / Slide 5 Introduction /First Applet public class NotHelloWorldApplet extends JApplet { public void init() { Container contentPane = getContentPane(); JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER); contentPane.add(label); } } //NotHelloWorldApplet.java

6 COMP201 Topic 11 / Slide 6 l Compare with class NotHelloWorldFrame extends JFrame { public NotHelloWorldFrame() { setTitle("NotHelloWorld"); setSize(300, 200); Container contentPane = getContentPane(); contentPane.add(new NotHelloWorldPanel()); } public class NotHelloWorld { public static void main(String[] args) { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } Introduction /First Applet

7 COMP201 Topic 11 / Slide 7 l Applets are created, run, and destroyed by web browser n Don’t set size for an applet: determined by HTML file. n Don’t set title for an applet: applets cannot have title bars. No need to explicitly construct an applet. Construction code placed inside the init method. There is no main method. n An applet cannot be closed. It terminates automatically when the browser exit. No need to call method show. An applet is displayed automatically. Introduction /First Applet

8 COMP201 Topic 11 / Slide 8 Introduction / Running An Applet 1. Compile the.java file 2. Create a HTML file that tells the browser which file to load and how to size the applet This is an example. This text shown if browser doesn’t do Java. 3. View the HTML file with a browser or the command appletviewer (for testing). This works for applets extending Applet, but doesn’t work for those that extend JApplet

9 COMP201 Topic 11 / Slide 9 Introduction / Running An Applet l Browser retrieves class file and automatically runs it using its JVM. l Problem: JVM of browsers does not support newest versions of Java (i.e. IDK 1.2 JDK 1.3) l Sun’s solution: require users to install the latest Java plug-in. (see http://java.sun.com/products/plugin/index.html )

10 COMP201 Topic 11 / Slide 10 Introduction / Running An Applet l Special HMTL tags needed for running applets with Java plug-in. l The use of those special tags is not straightforward. l Solution: 1. Write HTML file using traditional tags 2. Feeds it to HTML converter to produces a new HTML file with the special tags. 3. View the new HTML file. l Get the HMTL converter from course page (Online resources). Example of HTML file produced by converter ( NotHelloWordApplet.html )

11 COMP201 Topic 11 / Slide 11 Applet Basics / Class Loader and JAR Files l In the previous example, we have one classes NotHelloWorldApplet.class, l Name of the applet class is placed in HTML file Class loader first fetches NotHelloWorldApplet.class In the process, if the class loader notices that some other classes are also needed. It then makes another net connection to get them. l Many connections might be needed in general, especially when there are associated resources such as images and sounds. l Java Archive (JAR) files allow one to bundle a set of classes and resources into one file that can be downloaded via one net connection.

12 COMP201 Topic 11 / Slide 12 Applet Basics / Class Loader and JAR Files Create JAR file with command jar jar cf myJarFile.jar *.class *.gif pack all files ending with.class or.gif Refer to JAR files in the APPLET tag <applet archive=“myJarFile.jar” code=“MyApplet.class”” width=300 height=300> (see TetrixAppletJar.html and run TetrixAppletJar) l JAR file is downloaded via one net connection. l Class loader tries to find necessary files in JAR file before attempting to get them from the net.

13 COMP201 Topic 11 / Slide 13 Diversion/Self-Running Jar File “ jar cfm …” creates a jar file and a manifest file./META_INF/MANIFEST.MF l It describes features of the archive. l To make an executable jar file, we need to indicate the main class in the manifest file. Make mainclass.txt with one line ( no “ class ” and ended by “ return ”) Main-Class: MyApplet n Update the manifest variable jar umf mainclass.txt MyJarFile.jar l Run: n java -jar MyJarFile.jar n Or click on file icon Self-Running Tetrix Jar

14 COMP201 Topic 11 / Slide 14 Applet Basics / Security l Applets are downloaded from the net and executed by a browser’s JVM immediately. l User never gets a chance to confirm or to stop an applet from running. l Consequently, applets are restricted in what they can do. The applet security manager is responsible for enforcing access rules and throws an SecurityException when an access rule is violated.

15 COMP201 Topic 11 / Slide 15 Applet Basics / Security l By default, an applet is restricted to run “inside the sandbox”. Strictest security restrictions. l Signed applets can have more access privileges. l For now, we consider only applets playing in the sandbox.

16 l Access rights for Applets and Java Applications (JA) BR: applets running inside a browser with default applet security model AV: applets running insider Applet viewer BR Read local file N Write local file N Get file info. N Delete file N Run another program N Read theuser.name property N Connect to network port on home server Y Connect to network port on other server N Load Java library N Call exit N Create a pop-up window warning AVJA YY YY YY NY YY YY YY YY YY YY YY

17 COMP201 Topic 11 / Slide 17 Applet Basics / Applet Life Cycle An application starts from main and runs until exit Applets are controlled by browser –Born when their pages are first loaded –Respond to messages and user inputs when visible –“Turned off” when not visible –Disposed by browser either when changing page or quitting Change behavior by overriding methods: –init(); start(), stop() & destroyed() All those methods are called automatically

18 COMP201 Topic 11 / Slide 18 Applet Basics / Applet Life Cycle public void init() –One-time initialization when first loaded –Good place to process parameters and add interface components. public void start() –Called whenever user returns to the page containing the applet after having gone off to other pages. –Can be called multiple times. –Good place to resume animation or game

19 COMP201 Topic 11 / Slide 19 Applet Basics / Applet Life Cycle public void stop() –Called when user moves off page –Good place to stop time-consuming activities such as animation and audio playing. public void destroy() –Called when browser shuts down. –Good place to reclaim non-memory-dependent resources such as graphics contexts. –Normally, no need to worry.

20 COMP201 Topic 11 / Slide 20 Converting Applications to Applets l Java applications can easily to converted into applets l Non-IO codes stay essentially the same. l Inputs from home server are easy to handle. l Outputs to home server are more advanced (CGI, Servlet). l (Applets cannot communicate with other servers. “Applets can only phone home”. If applets are to communicate with other servers, including the local server, more access rights have to be given using a security policy file.) l Non-IO applications first. 1. Pop up a window for application 2. Place top-level frame of application inside a browser

21 COMP201 Topic 11 / Slide 21 Converting Applications to Applets l Popping up a window for application. l What to do: Assume: Separate class for creating and showing a top- level frame. (If this class also does some other things, move the other things to other classes.) class NotHelloWorldFrame extends JFrame {…} public class NotHelloWorld { public static void main(String[] args) { JFrame frame = new NotHelloWorldFrame(); frame.show(); }

22 COMP201 Topic 11 / Slide 22 Converting Applications to Popup Applets l Delete the class for creating and showing the top- level frame Add an applet class whose init method contains the same instructions as main method of deleted class. public class NHWApplet extends JApplet { public void init() { JFrame frame = new NotHelloWorldFrame(); frame.show(); } } //NHWApplet.class l The popup window coming with a warning message for security reasons, (which can be avoided for signed applets).

23 COMP201 Topic 11 / Slide 23 Converting Applications to embedded Applets l Placing top-level frame of application inside browser. What to do: (Assume: main is in the definition of the top-level frame & its only purpose is to create a window and show it. NotHelloWorld.java ) JFrame class => JApplet class; must be public Remove setSize: set in HTML file Remove addWindowListener: Applet cannot be closed Remove setTitle: Applet cannot have title bar Replace constructor with init. Delete the main method.

24 COMP201 Topic 11 / Slide 24 Converting Applications to embedded Applets class NotHelloWorldFrame extends JFrame { public NotHelloWorldFrame() { setTitle("NotHelloWorld"); setSize(300, 200); Container contentPane = getContentPane(); contentPane.add(new NotHelloWorldPanel()); } public class NotHelloWorld { public static void main(String[] args) { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }

25 COMP201 Topic 11 / Slide 25 Converting Applications to Applets public class NotHelloWorldApplet extends JApplet { public void init() { Container contentPane = getContentPane(); JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER); contentPane.add(label); } } //NotHelloWorldApplet.java

26 COMP201 Topic 11 / Slide 26 Resources for Applets l One can provide information to applets in HTML file l Applets can access resources at home server: l Text l Multimedia

27 COMP201 Topic 11 / Slide 27 Passing Info to Applets via HTML File l In HTML file, use PARAM, NAME, VALUE tags …. In applet, use the getParameter method of the Applet class getParameter("title"); // returns "Diameters of the Planets “ String vString = getParameter(“values”); // returns “9” if (vString == null ) {do something} // precaution else int v=Integer.parseInt(vString);//must parse to get numbers Chart.java, Chart.html

28 COMP201 Topic 11 / Slide 28 Accessing Resources at Home Server l Where is home? Inside a subclass of Applet getDocumentBase returns URL of the html file that calls the applet getCodeBase returns URL of the applet itself Inside any other class x x.class gives one an object of the Class class that contain information of x. ( Class is a special class and has method getResource. C.f. Object class) x.class.getResource( resourceName ) returns URL of resource Need the URL class in java.net package import java.net.*

29 COMP201 Topic 11 / Slide 29 Accessing Text Files at Home Server Find the URL of text file and the create an InputStream using the openStream method of URL class InputStream in = url.openStream(); Or create an InputStream directly using the getResourceAsStream method of the Class class. InputStream in = x.class.getResoruceAsStream( fileName); The InputStream can be nested with other streams in the normal way (see Topic 4) ResourceTest.java, ResourceTest.html

30 COMP201 Topic 11 / Slide 30 l Applets can handle images in GIF or JPEG format l Load images Inside an subclass Applet, use getImage(url), getImage(url, name) Inside other classes java.awt.Toolkit Toolkit.getDefaultToolkit().getImage( url ); l How to show an image? ImageLoadApplet.java Accessing Images at Home Server Exercise: Load the images in applet class

31 COMP201 Topic 11 / Slide 31 l Applets can handle audio files in AU, AIFF, WAV, or MIDI format. Audio Clips (java.applet.Applet) Load: AudioClip getAudioClip(url), AudioClip getAudioClip(url, name) Then use play method of AudioClip to play and the stop method to stop Play without first loading: void play(url), void play(url, name) //SoundApplet.java Accessing Audio Files at Home Server

32 COMP201 Topic 11 / Slide 32 Communication with Browser To establish a communication channel between an applet and browser, use the getAppletContext method of the Applet class The method returns an object of the AppletContext, which is an interface. Two useful methods of interface AppletContext showDocument( URL url ) showDocument(URL url, String target ) ShowPageApplet.java

33 COMP201 Topic 11 / Slide 33 Weird Trick: To avoid the additional HTML file, one can add an applet tag as a comment inside the source file. /* */ public class MyApplet extends Japplet … l Then run the applet viewer with the source file as its command line arguments: Appletviewer MyApplet.java l Not necessarily recommending this as standard practice. But it is handy during testing.


Download ppt "COMP201 Java Programming Part II: GUI Programming Topic 11: Applets Chapter 10."

Similar presentations


Ads by Google