COMP201 Java Programming - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

COMP201 Java Programming

Description:

So far, we've only covered topics related to stand-alone applications. An applet is designed to run within a browser ... Diversion/Self-Running Jar File ' ... – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 34
Provided by: CSD149
Category:

less

Transcript and Presenter's Notes

Title: COMP201 Java Programming


1
COMP201 Java Programming Part II GUI Programming
Topic 11 Applets Chapter 10
2
Outline
  • Introduction
  • What are applets?
  • How to run?
  • Applets basics
  • Class loader and JAR files
  • Security basics
  • Applet life cycle
  • Converting applications to applets
  • Resources for applets
  • Communication with browser

3
Introduction
  • So far, weve only covered topics related to
    stand-alone applications
  • An applet is designed to run within a browser
  • Bring web pages to life
  • 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
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
  • Event handling exactly the same as before

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
Introduction/First Applet
  • 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()

7
Introduction/First Applet
  • Applets are created, run, and destroyed by web
    browser
  • Dont set size for an applet determined by HTML
    file.
  • Dont 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.
  • An applet cannot be closed. It terminates
    automatically when the browser exit.
  • No need to call method show. An applet is
    displayed automatically.

8
Introduction/Running An Applet
  • Compile the .java file
  • 2. Create a HTML file that tells the browser
    which file to load and how to size the applet
  • lthtmlgtltbodygt This is an example.
  • ltapplet codeNotHelloWorldApplet.class
    width300 height300gt
  • This text shown if browser doesnt do Java.
  • lt/appletgt
  • lt/bodygtlt/htmlgt
  • View the HTML file with a browser or the command
    appletviewer (for testing).
  • This works for applets extending Applet,
    but doesnt work for those that extend JApplet

9
Introduction/Running An Applet
  • Browser retrieves class file and automatically
    runs it using its JVM.
  • Problem JVM of browsers does not support newest
    versions of Java (i.e. IDK 1.2 JDK 1.3)
  • Suns solution require users to install the
    latest Java plug-in.
  • (see http//java.sun.com/products/plugin/index.h
    tml)

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

11
Applet Basics/Class Loader and JAR Files
  • In the previous example, we have one classes
  • NotHelloWorldApplet.class,
  • Name of the applet class is placed in HTML file
  • Class loader first fetches NotHelloWorldApplet.cla
    ss
  • In the process, if the class loader notices that
    some other classes are also needed. It then makes
    another net connection to get them.
  • Many connections might be needed in general,
    especially when there are associated resources
    such as images and sounds.
  • 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
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
  • ltapplet archivemyJarFile.jar
  • codeMyApplet.class width300 height300gt
  • (see TetrixAppletJar.html and run
    TetrixAppletJar)
  • JAR file is downloaded via one net connection.
  • Class loader tries to find necessary files in JAR
    file before attempting to get them from the net.

13
Diversion/Self-Running Jar File
  • jar cfm creates a jar file and a manifest
    file ./META_INF/MANIFEST.MF
  • It describes features of the archive.
  • 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
  • Update the manifest variable
  • jar umf mainclass.txt MyJarFile.jar
  • Run
  • java -jar MyJarFile.jar
  • Or click on file icon

Self-Running Tetrix Jar
14
Applet Basics/Security
  • Applets are downloaded from the net and executed
    by a browsers JVM immediately.
  • User never gets a chance to confirm or to stop an
    applet from running.
  • 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
Applet Basics/Security
  • By default, an applet is restricted to run
    inside the sandbox. Strictest security
    restrictions.
  • Signed applets can have more access privileges.
  • For now, we consider only applets playing in the
    sandbox.

16
  • 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
AV
JA
Read local file
N
Y
Y
Write local file
N
Y
Y
Get file info.
N
Y
Y
Delete file
N
N
Y
Run another program
N
Y
Y
Read the
user.name property
N
Y
Y
Y
Y
Y
Connect to network port on home server
Connect to network port on other server
N
Y
Y
Load Java library
N
Y
Y
Call exit
N
Y
Y
Create a pop-up window
warning
Y
Y
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
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
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
Converting Applications to Applets
  • Java applications can easily to converted into
    applets
  • Non-IO codes stay essentially the same.
  • Inputs from home server are easy to handle.
  • Outputs to home server are more advanced (CGI,
    Servlet).
  • (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.)
  • Non-IO applications first.
  • Pop up a window for application
  • Place top-level frame of application inside a
    browser

21
Converting Applications to Applets
  • Popping up a window for application.
  • 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
Converting Applications to Popup Applets
  • 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
  • The popup window coming with a warning message
    for security reasons, (which can be avoided for
    signed applets).

23
Converting Applications to embedded Applets
  • 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 gt 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
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_CLOS
E) frame.show()
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
Resources for Applets
  • One can provide information to applets in HTML
    file
  • Applets can access resources at home server
  • Text
  • Multimedia

27
Passing Info to Applets via HTML File
  • In HTML file, use PARAM, NAME, VALUE tags
  • ltAPPLET CODE"Chart.class" WIDTH400 HEIGHT300gt
  • ltPARAM NAME"title" VALUE"Diameters of the
    Planets"gt
  • ltPARAM NAME"values" VALUE"9"gt
  • . lt/Appletgt
  • 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 vInteger.parseInt(vString)//must parse
    to get numbers

Chart.java, Chart.html
28
Accessing Resources at Home Server
  • 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
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
Accessing Images at Home Server
  • Applets can handle images in GIF or JPEG format
  • Load images
  • Inside an subclass Applet, use
  • getImage(url), getImage(url, name)
  • Inside other classes java.awt.Toolkit
  • Toolkit.getDefaultToolkit().getImage( url )
  • How to show an image?

ImageLoadApplet.java
Exercise Load the images in applet class
31
Accessing Audio Files at Home Server
  • 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

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
Weird Trick
  • To avoid the additional HTML file, one can add an
    applet tag as a comment inside the source file.
  • /
  • ltAPPLET CODE MyApplet.class WIDTH300
    HEIGHT300gt
  • lt/APPLETgt
  • /
  • public class MyApplet extends Japplet
  • Then run the applet viewer with the source file
    as its command line arguments
  • Appletviewer MyApplet.java
  • Not necessarily recommending this as standard
    practice. But it is handy during testing.
Write a Comment
User Comments (0)
About PowerShow.com