1 / 39

Writing Applets

Writing Applets. Base on : The Java Tutorial Object-Oriented Programming for the Internet. Overview of Applets Creating an Applet User Interface Communicating with Other Programs Understanding Applet Capabilities and Restrictions Finishing an Applet

saima
Download Presentation

Writing Applets

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Writing Applets Base on : The Java Tutorial Object-Oriented Programming for the Internet • Overview of Applets • Creating an Applet User Interface • Communicating with Other Programs • Understanding Applet Capabilities and Restrictions • Finishing an Applet • Common Applet Problems (and Their Solutions)

  2. Overview of Applets • Every applet is implemented by creating a subclass of the Applet class. • The following figure shows the inheritance hierarchy of the Applet class. java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet

  3. A Simple Applet • A Simple Applet import java.applet.Applet; import java.awt.Graphics; public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); //AWT.Component } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, size().width - 1, size().height - 1); //Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } }

  4. The Life Cycle of an Applet • Loading the Applet – When an applet is loaded, here's what happens: • An instance of the applet's controlling class (an Applet subclass) is created. • The applet initializes itself. • The applet starts running.

  5. The Life Cycle of an Applet • Leaving and Returning to the Applet's Page • When the user leaves the page, the applet has the option of stopping itself. • When the user returns to the page, the applet can start itself again. • The same sequence occurs when the user iconifies and then reopens the window that contains the apple.

  6. The Life Cycle of an Applet • Reloading the Applet • Some browsers let the user reload applets, which consists of unloading the applet and then loading it again. • Before an applet is unloaded, it's given the chance to stop itself and then to perform a final cleanup, so that the applet can release any resources it holds. • After that, the applet is unloaded and then loaded again.

  7. The Life Cycle of an Applet • Quitting the Browser • When the user quits the browser, the applet has the chance to stop itself and do final cleanup before the browser exits. • Summary - An applet can react to major events in the following ways: • It can initialize itself. • It can start running. • It can stop running. • It can perform a finalcleanup, in preparation for being unloaded.

  8. Methods for Milestones • init()– • To initialize the applet each time it's loaded (or reloaded). • The init() class is useful for one-time initialization that doesn't take very long. • In general, the init() method should contain the code that you would normally put into a constructor.

  9. Methods for Milestones • start()– • To start the applet's execution, such as when the applet's loaded or when the user revisits a page that contains the applet. • Every applet that does something after initialization (except in direct response to user actions) must override the start() method. • The start() method either performs the applet's work or (more likely) starts up one or more threads to perform the work.

  10. Methods for Milestones • stop()– • To stop the applet's execution, such as when the user leaves the applet's page or quits the browser. • Most applets that override start() should also override the stop() method. • The stop() method should suspend the applet's execution, so that it doesn't take up system resources when the user isn't viewing the applet's page.

  11. Methods for Milestones • destroy() – • To perform a final cleanup in preparation for unloading. • Many applets don't need to override the destroy() method, since their stop() method (which is called before destroy()) does everything necessary to shut down the applet's execution. • However, destroy() is available for applets that need to release additional resources

  12. Methods for Drawing and Event Handling • There are two display methods that applets can override: • paint() • The basic display method. Many applets implement the paint() method to draw the applet's representation within a browser page. • update() • A method you can use along with paint() to improve drawing performance.

  13. Methods for Drawing and Event Handling • Applets inherit their paint() and update() methods from the Appletclass, which inherits them from the AbstractWindowToolkit (AWT) Component class. class Simple extends Applet { . . . public void paint(Graphics g) { . . . } . . . }

  14. Methods for Drawing and Event Handling • From the Component class, applets inherit a group of methods for event handling. • The Component class defines several methods (such as mouseDown() and action()) for handling particular types of events, and then one catch-all method, handleEvent().

  15. Methods for Drawing and Event Handling • To react to an event, an applet must override either the handleEvent() method or the appropriate specialized method. • For example, adding the following code to the Simple applet makes it respond to mouse clicks. import java.awt.Event; . . . public boolean mouseDown(Event event, int x, int y) { addItem("click!... "); return true; }

  16. Methods for Adding UI Components • The AWT supplies the following UI components : • Buttons (java.awt.Button) • Checkboxes (java.awt.Checkbox) • Single-line text fields (java.awt.TextField) • Larger text display and editing areas (java.awt.TextArea) • Labels (java.awt.Label) • Lists (java.awt.List) • Pop-up lists of choices (java.awt.Choice) • Sliders and scrollbars (java.awt.Scrollbar) • Drawingareas (java.awt.Canvas) • Menus (java.awt.Menu, java.awt.MenuItem, java.awt.CheckboxMenuItem) • Containers (java.awt.Panel, java.awt.Window and its subclasses)

  17. Methods for Using UI Components in Applets • The Applet class inherits from the AWT Container class, it's easy to add components to applets and to use layout managers to control the their onscreen positions. Some of the Container methods an applet can use: • add() • Adds the specified Component. • remove() • Removes the specified Component. • setLayout() • Sets the layout manager.

  18. Adding a Non-Editable Text Field to an Applet • To make the Simple applet use a scrolling, non-editable text field, we can use the TextField class. • Here is the revised sourcecode. • The revised init() method creates an uneditable text field (a TextField instance). • It sets the applet's layout manager to one that makes the text field as wide as possible and then adds the text field to the applet.

  19. Threads in Applets • A thread -- sometimes known as an executioncontext or a lightweightprocess -- is a single sequential flow of control within a process. • Even the simplest applets run in multiple threads, although it's not always apparent. • Many applets create and use their own threads, so that they perform well without affecting the performance of the application they run in or of other applets.

  20. Threads in Applets • Every applet can run in multiple threads. • Applet drawing methods (paint() and update()) are always called from the AWT drawing and event handling thread. • The threads from which the major milestone methods -- init(), start(), stop(), and destroy() -- are called depends on the application that's running the applet.

  21. Threads in Applets • PrintThreadis a modified version of SimpleApplet that prints the thread and thread group that its init(), start(), stop(), destroy(), and update() methods are called from.

  22. Threads in Applets • Rule of Thumb: An applet performing a time-consuming task should create and use its own thread to perform that task. • Applets typically perform two kinds of time-consuming tasks: tasks that they perform once, and tasks that they perform repeatedly.

  23. Threads in Applets: Examples • The first applet, AnimatorApplet, shows how to use a thread to perform repeated tasks. • The second applet, SoundExample, shows how to use threads for one-time initialization tasks.

  24. Using a Thread to Perform Repeated Tasks • Applets typically create threads for repetitive tasks in the applet start() method. • Creating the thread there makes it easy for the applet to stop the thread when the user leaves the page. • All you need to do is implement the stop() method so that it stops the applet's thread. An Animator example

  25. Using a Thread to Perform Repeated Tasks public void start() { if (frozen) { //Do nothing. The user has requested that we //stop changing the image. } else { //Start animating! if (animatorThread == null) { animatorThread = new Thread(this); } animatorThread.start(); } } public void stop() { animatorThread = null; } No garbage collect on this. Click Here to see the source

  26. Using a Thread to Perform One-Time Initialization • If an applet needs to perform some initialization task that can take a while, it should consider performing the initialization in a thread. • For example, anything that requires making a network connection should generally be done in a background thread.

  27. Using a Thread to Perform One-Time Initialization • Fortunately, GIF and JPEG image loading is automatically done in the background (using threads that you don't need to worry about). • Sound loading unfortunately, is not guaranteed to be done in the background. • The Applet getAudioClip methods don't return until they've loaded all the audio data.

  28. Using a Thread to Perform One-Time Initialization • SoundExample adheres closely to the model presented in Synchronizing Threads. • The producer: SoundLoader, a Thread subclass. • The consumer: SoundExample, an Applet subclass. • The storage object: SoundList, a Hashtable subclass.

  29. What Applets Can and Can't Do • For security reasons, applets that are loaded over the network have several restrictions. • One is that an applet can't ordinarily read or write files on the computer that it's executing on. • Another is that an applet can't make network connections except to the host that it came from.

  30. Security Restrictions • Current browsers impose the following restrictions on any applet that's loaded over the network: • An applet can't load libraries or define native methods. • It can't ordinarily read or write files on the host that's executing it. • It can't make network connections except to the host that it came from.

  31. Security Restrictions • Current browsers impose the following restrictions on any applet that's loaded over the network: • It can't start any program on the host that's executing it. • It can't read certain system properties. • Windows that an applet brings up look different than windows that an application brings up.

  32. Security Restrictions • Every browser implements securitypolicies to keep applets from doing damage. • Each browser has a SecurityManager object that implements its security policies. • When a SecurityManager detects a violation, it throws a SecurityException. • Your applet can catch this SecurityException and react appropriately.

  33. Applet Capabilities • The java.applet package provides an API that gives applets some capabilities that applications don't have: • Applets can make network connections to the host they came from. • Applets running within a Web browser can easily cause HTML documents to be displayed. • Applets can invoke public methods of other applets on the same page.

  34. Applet Capabilities • The java.applet package provides an API that gives applets some capabilities that applications don't have: • Applets that are loaded from the local file system (from a directory in the user's CLASSPATH) have none of the restrictions that applets loaded over the network do. • Although most applets stop running once you leave their page, they don't have to.

  35. Adding an Applet to an HTML Page • Here's the simplest form of the <APPLET> tag: <APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt> </APPLET>

  36. Specifying the Applet Directory with CODEBASE • Add a CODEBASE attribute to tell the browser/viewer which directory the Applet subclass bytecodes are in. <APPLET CODE=AppletSubclass.class CODEBASE=aURL WIDTH=anInt HEIGHT=anInt> </APPLET> • By making aURL an absoluteURL, you can make a document loaded from your HTTP server run an applet from another HTTP server. • When aURL is a relative URL…..

  37. Specifying Parameters with the <PARAM> Tag • You can customize the applet's configuration with parameters. For example, you can set a button's text by specifying the value of a parameter named BUTTONTEXT. • Note that <PARAM> tags must appear between the <APPLET> and </APPLET> tags for the applet they affect.

  38. Specifying Parameters with the <PARAM> Tag <APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt> <PARAM NAME=parameter1Name VALUE=aValue> <PARAM NAME=parameter2Name VALUE=anotherValue> </APPLET> <applet code=AppletButton.class codebase=example width=350 height=60> <param name=windowType value=BorderWindow> <param name=windowText value="BorderLayout"> <param name=buttonText value="Click here to see a BorderLayout in action"> . . . </applet>

  39. Specifying Text to be Displayed by Java-Deficient Browsers <applet code=AppletButton.class codebase=example width=350 height=60> <param name=windowType value=BorderWindow> <param name=windowText value="BorderLayout"> <param name=buttonText value="Click here to see a BorderLayout in action"> <blockquote> <hr> <em>Your browser can't run 1.0 Java applets, so here's a picture of the window the program brings up: </em> <p> <img src=images/BorderEx1.gif width=302 height=138> <hr> </blockquote> </applet>

More Related