Download presentation
Presentation is loading. Please wait.
1
COMP201 Java Programming Part II: GUI Programming Topic 11: Applets Chapter 10
2
COMP201 Topic 11 / Slide 2 Introduction l Applets are java programs that run within browsers l Example: n Jmol applet –http://jmol.sourceforge.net/applet/ n NASA 3D real-time satellite tracker –http://liftoff.msfc.nasa.gov/realtime/jtrack/3d/JTrack3d.htmlhttp://liftoff.msfc.nasa.gov/realtime/jtrack/3d/JTrack3d.html Applet Client BrowserServer Applet User
3
COMP201 Topic 11 / Slide 3 Outline l An example l Creation n Converting applications to applets l Transportation n Jar files: Move applets from servers to browsers quickly l Operation n Applet life cycle n Security restrictions n Getting resources from home n Communicating with browser Applet Client BrowserServer Applet User
4
COMP201 Topic 11 / Slide 4 An Example An applet is a Java class which extends java.applet.Applet If Swing components are used, the applet must extend from javax.swing.JApplet 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
5
COMP201 Topic 11 / Slide 5 l Compile and run Compile: javac NotHelloWorldApplet.java n Run: –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. –View the HTML file with a browser or the command appletviewer n Note: –Textpad: Cntrl+3 – creates a simple html file and show it with appletviewer An Example
6
COMP201 Topic 11 / Slide 6 An Example l More notes n To view applet, one needs Java 2 enabled browser (recent version of IE and Netscape, e.g. IE 6, Netscape 6, Netscape 7. Netscape 4 is not Java 2 enabled) n Class files are cached by browser. –Restart browser after each modification –Alternatively, one can clear the cache from Java console, which can be accessed from Netscape or control panel on Windows
7
COMP201 Topic 11 / Slide 7 An Example
8
COMP201 Topic 11 / Slide 8 l Compare with application: NotHelloWorld.java class NotHelloWorldFrame extends JFrame { public NotHelloWorldFrame() { setTitle("NotHelloWorld"); setSize(300, 200); Container contentPane = getContentPane(); JLabel label = new JLabel("Not a Hello, World application", SwingConstants.CENTER); contentPane.add(label); } public class NotHelloWorldApplication { public static void main(String[] args) { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }} An Example
9
COMP201 Topic 11 / Slide 9 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. –Can have menus. 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. An Example
10
COMP201 Topic 11 / Slide 10 Outline l An example l Creation n Converting applications to applets l Transportation n Jar files: Move applets from servers to browsers quickly l Operation n Applet life cycle n Security restrictions n Getting resources from home n Communicating with browser
11
COMP201 Topic 11 / Slide 11 Creating Applets from Applications l Non-IO applications for now n Pop up window for application n Embed top-level frame of application inside browser
12
COMP201 Topic 11 / Slide 12 Creating Applets from Applications l Popping up a window for application. n 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 NotHelloWorldApplication { public static void main(String[] args) { JFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }
13
COMP201 Topic 11 / Slide 13 l Steps of conversion: n 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. n Remove code for closing window public class NHWApplet extends JApplet { public void init() { JFrame frame = new NotHelloWorldFrame(); frame.show(); } } //NHWApplet.java n The popup window coming with a warning message for security reasons, (which can be avoided for signed applets). Creating Applets from Applications
14
COMP201 Topic 11 / Slide 14 l Placing top-level frame of application inside browser. n 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 NotHelloWorldFrame() { setTitle("NotHelloWorld"); setSize(300, 200); Container contentPane = getContentPane(); JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER); contentPane.add(label); }} public class NotHelloWorld { public static void main(String[ ] args) { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }} Creating Applets from Applications
15
COMP201 Topic 11 / Slide 15 l Steps of conversion n Delete the class for creating and showing the top-level frame n Convert the top-level frame class into an applet –JFrame class => JApplet class; must be public –Remove setSize: set in HTML file –Remove setTitle: Applet cannot have title bar –Replace constructor with init. Creating Applets from Applications
16
COMP201 Topic 11 / Slide 16 l Let’s do it now class NotHelloWorldFrame extends JFrame { public NotHelloWorldFrame() { setTitle("NotHelloWorld"); setSize(300, 200); Container contentPane = getContentPane(); JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER); contentPane.add(label); }} public class NotHelloWorld { public static void main(String[ ] args) { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }} Creating Applets from Applications
17
COMP201 Topic 11 / Slide 17 Outline l An example l Creation n Converting applications to applets l Transportation n Jar files: Move applets from servers to browsers quickly l Operation n Applet life cycle n Security restrictions n Getting resources from home n Communicating with browser
18
COMP201 Topic 11 / Slide 18 Transportation of Applets via Jar Files l PopupCalculatorApplet involve three classes n CalculatorFrame.class, CalculatorPanel.class PopupCalculatorApplet.class l HTML file contains name of the applet class n l Class loader First fetches PopupCalculatorApplet.class In the process, it notices that some other classes are also needed. It then makes net connections to get them. n Many connections might be needed in general, especially when there are associated resources such as images and sounds.
19
COMP201 Topic 11 / Slide 19 Jar Files l Jar files n A jar file is simply a zip file that contains a manifest file, which describes features of the archive n 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.
20
COMP201 Topic 11 / Slide 20 Jar Files l Creating jar files n jar cf PopupCalculatorAppletClasses.jar *class l In general: jar cf myJarFile.jar *.class *.gif pack all files ending with.class or.gif
21
COMP201 Topic 11 / Slide 21 Jar Files Refer to JAR files in the APPLET tag <APPLET CODE="PopupCalculatorApplet.class" ARCHIVE="PopupCalculatorAppletClasses.jar,swing.jar" WIDTH = 65 HEIGHT = 20 > 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.
22
COMP201 Topic 11 / Slide 22 Diversion/Self-Running Jar File l “To make an executable jar file, we need to indicate the main class in the manifest file. Create “mainclass.mf” with one line ( no “ class ” and ended by “ return ”) Main-Class: MyApplet n Create jar file with the manifest file jar cvfm MyJarFile.jar mainclass.mf *class n Also, one can update the manifest files of an existing jar file jar umf mainclass.mf MyJarFile.jar l Run: n java -jar MyJarFile.jar n Or click on file icon Self-Running Calculator
23
COMP201 Topic 11 / Slide 23 Outline l An example l Creation n Converting applications to applets l Transportation n Jar files: Move applets from servers to browsers quickly l Operation n Applet life cycle n Security restrictions n Getting resources from home n Communicating with browser
24
COMP201 Topic 11 / Slide 24 Applet Life Cycle l An application starts from main and runs until exit l Applets are controlled by browser through 4 methods n init() –Called when loaded by browser n start() –Called right after init and when user return to page n stop() –Called when user moves off page n destroy() –Called when browser shuts down. l Overwrite the methods to control applet behavior non-existenton page off page init( ) destroy( ) stop( ) destroy( )start( )
25
COMP201 Topic 11 / Slide 25 l public void init() n One-time initialization when first loaded n Good place to process parameters and add interface components. l public void start() n Called whenever user returns to the page containing the applet after having gone off to other pages. n Can be called multiple times. n Good place to resume animation or game Applet Life Cycle
26
COMP201 Topic 11 / Slide 26 l public void stop() n Called when user moves off page (to other pages) n Good place to stop time-consuming activities such as animation and audio playing. l public void destroy() n Called when browser shuts down. n Good place to reclaim non-memory-dependent resources such as graphics contexts. n Normally, no need to worry. l Example: sound (Stop Playing when going out of page) Compare with the one of the two other versions. Applet Life Cycle
27
COMP201 Topic 11 / Slide 27 Outline l An example l Creation n Converting applications to applets l Transportation n Jar files: Move applets from servers to browsers quickly l Operation n Applet life cycle n Security restrictions n Getting resources from home n Communicating with browser
28
COMP201 Topic 11 / Slide 28 Security Restrictions 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.
29
COMP201 Topic 11 / Slide 29 Security Restriction 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.
30
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
31
COMP201 Topic 11 / Slide 31 Outline l An example l Creation n Converting applications to applets l Transportation n Jar files: Move applets from servers to browsers quickly l Operation n Applet life cycle n Security restrictions n Getting resources from home n Communicating with browser Applet Client BrowserServer Applet User
32
COMP201 Topic 11 / Slide 32 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
33
COMP201 Topic 11 / Slide 33 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
34
COMP201 Topic 11 / Slide 34 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.*
35
COMP201 Topic 11 / Slide 35 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
36
COMP201 Topic 11 / Slide 36 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
37
COMP201 Topic 11 / Slide 37 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
38
COMP201 Topic 11 / Slide 38 Outline l An example l Creation n Converting applications to applets l Transportation n Jar files: Move applets from servers to browsers quickly l Operation n Applet life cycle n Security restrictions n Getting resources from home n Communicating with browser Applet Client BrowserServer Applet User
39
COMP201 Topic 11 / Slide 39 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
40
COMP201 Topic 11 / Slide 40 Java Web Start l A technology for simplifying deployment of Java applications n Gives you the power to launch full-featured applications with a single click from your Web browser. n The Java Web Start software is the reference implementation for the Java Network Launching Protocol (JNLP) n http://java.sun.com/products/javawebstart/docs/developersguide.html
41
COMP201 Topic 11 / Slide 41 Java Web Start l What do you need? n Jar files that contain class files & resources. n A jnlp file for the application n A link from the Web page to the JNLP file n Configure the Web server so that the.jnlp file extension invokes Web Start.(http://java.sun.com/products/javawebstart/docs/developersguide.html#w ebsite)http://java.sun.com/products/javawebstart/docs/developersguide.html#w ebsite l Client side: n Install Java Web Start, included in Download J2SE 5.0 JRE/SDK (jdk1.5.1) Download J2SE 5.0 JRE/SDK
42
COMP201 Topic 11 / Slide 42 Java Web Start l Example 1 (javaWebStartExamples.zip): n NotHelloWorld.jar generated from NotHelloWorld.java n NotHelloWorld.jnlp See next page n index.html NotHelloWorld Application
43
COMP201 Topic 11 / Slide 43 Java Web Start n NotHelloWorld.jnlp <jnlp codebase="http://www.cs.ust.hk/~lzhang/teach/java03/webStart" href="NotHelloWorld.jnlp"> NotHelloWorld Application Sun Microsystems, Inc. NotHelloWorld Application A demo of nothing useful
44
COMP201 Topic 11 / Slide 44 Java Web Start l Unlike applets, web-start applications have a main() like normal Java applications. There are a few special requirements: l The application must be contained in a jar file l By default restricted to Sandbox as Applets (cannot call standard IO libaries to access the disk, you can only connect back the source host etc). l Resources (files, images) must also be in a jar file and must be accessed using the getResource() method. l Like applets users can grant more access if they trust your code l A JNLP API is required for some applications.
45
COMP201 Topic 11 / Slide 45 Java Web Start l Web-start applications differ from applets in several ways: n They are stored in the local disk so do not need to be downloaded each time. n They can call System.exit(). n They do not have the same lifecycle. n A web-start application can use a special class library which allows the application to prompt users to approve reading and writing to/from the local disk. n Rather than HMTL tags in a web-page, XML (JNLP) is used to describe web-start applications.
46
COMP201 Topic 11 / Slide 46 Java Web Start l Example 2: ImageTest n ImageTest.java –Loading image using the getResource method n ImageTest.jar –Includes class files & image files n ImageTest.jnlp n Index.html ImageTest Application
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.