applets life cycle drawing and event handling methods for ui components applet capabilities example

28
Applets • Life Cycle • Drawing and Event Handling • Methods for UI Components • Applet Capabilities • Example

Upload: giles-ward

Post on 12-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Applets

• Life Cycle

• Drawing and Event Handling

• Methods for UI Components

• Applet Capabilities

• Example

Page 2: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Life Cycle

• Loading the applet– instance of applet subclass is created– applet initializes itself [init()] (like constructor)– applet starts running [start()] (execution,

except user input)

• Leave and Come Back– stopping [stop()]– restarting [start()]– iconification [minimize]

Page 3: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

•Reloading the Applet

•Quitting the Browser

–stop()

–final cleanup [destroy()]

•init, start, stop, destroy methods

Page 4: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

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(); }

public void paint(Graphics g) {//Draw a Rectangle around the applet's display area.

g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);

//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); }}

Page 5: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Drawing and Event Handling

• paint(): Basic display method.

• update(): method used with paint() to improve performance

• Objects notified of registered events (listen for them)

• Register event by implementing appropriate interface (mouseListener)

Page 6: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

import java.awt.event.MouseListener;import java.awt.event.MouseEvent;import java.applet.Applet;import java.awt.Graphics;

public class SimpleClick extends Applet implements MouseListener {

StringBuffer buffer;

public void init() {addMouseListener(this);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(); }

public void paint(Graphics g) {//Draw a Rectangle around the applet's display area.

g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);

//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); }

//The following empty methods can be removed //by implementing a MouseAdapter (usually done //using an inner class). public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { }

public void mouseClicked(MouseEvent event) {

Page 7: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

•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) •Drawing areas (java.awt.Canvas) •Menus (java.awt.Menu, java.awt.MenuItem, java.awt.CheckboxMenuItem) •Containers (java.awt.Panel, java.awt.Window and its subclasses)

Pre-Made AWT UI Components

Page 8: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Adding UI Components

• add: adds the component to the applet

• remove: removes the component

• setLayout: sets the applet’s layout manager which controls the position and size of the applet components

Page 9: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

import java.applet.Applet;import java.awt.TextField;

public class ScrollingSimple extends Applet {

TextField field;

public void init() { //Create the text field and make it uneditable. field = new TextField(); field.setEditable(false);

//Set the layout manager so that the text field will be//as wide as possible.

setLayout(new java.awt.GridLayout(1,0));

//Add the text field to the applet. add(field); validate(); //this shouldn't be necessary

addItem("initializing... "); }

public void start() { addItem("starting... "); }

public void stop() { addItem("stopping... "); }

public void destroy() { addItem("preparing for unloading..."); }

void addItem(String newWord) { String t = field.getText(); System.out.println(newWord); field.setText(t + newWord); }}

Page 10: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Working with Applets

• Cannot load libraries or define native methods• Cannot read or write files on local host• Cannot make network connections• Cannot start a program on local host• Cannot read system properties on local host• Implemented with SecurityManager which

throws SecurityExceptions

Page 11: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Applets Can...

• Display html

• If local, restrictions off

• make network connections back to host they came from

• Don’t have to stop when you leave

Page 12: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

<APPLET CODE = AppletSubclass.classWIDTH=anInt HEIGHT=anInt>

</APPLET>

Page 13: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Finding and Loading Data Files

Page 14: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

• Applet.getCodeBase() returns URL of directory from which applet classes load

• Applet.getDocumentBase() returns URL of directory from which applet’s html came

• Image image=getImage(getCodeBase(),"imgDir/a.gif");

Page 15: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Showing Status

• Applet.showStatus(String s);• showStatus("MyApplet: Loading image file " + file);

Page 16: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Displaying Documents

• AppletContext class allows applet to interact with context (i.e. browser) in which it runs.

• Display in browser (won’t work with appletviewer)

• public void showDocument(java.net.URL url)

• public void showDocument(java.net.URL url, String targetWindow)

Page 17: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

"_blank" Display the document in a new, nameless window. "windowName" Display the document in a window named windowName.

This window is created if necessary. "_self" Display the document in the window and frame

that contain the applet. "_parent" Display the document in the applet's window but in

the parent frame of the applet's frame. If the applet frame has no parent frame, this acts the

same as "_self". "_top" Display the document in the applet's window but in

the top-level frame. If the applet's frame is the top-level frame, this acts the same as "_self".

Page 18: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

...//In an Applet subclass: urlWindow = new URLWindow(getAppletContext()); . . .

class URLWindow extends Frame { . . . public URLWindow(AppletContext appletContext) { . . . this.appletContext = appletContext; . . . } . . . public boolean action(Event event, Object o) { . . . String urlString = /* user-entered string */; URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { ...//Inform the user and return... }

if (url != null) { if (/* user doesn't want to specify the window */) { appletContext.showDocument(url); } else { appletContext.showDocument(url, /* user-specified window */); } } . . .

Page 19: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Sending Messages to Other Applets

• Same host, same directory, same page

• Find by name on same page

• Two ways to name applet

Page 20: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

1) By specifying a NAME attribute within the applet's <APPLET> tag. For example:

<APPLET CODEBASE=example/ CODE=Sender.class WIDTH=450 HEIGHT=200 NAME="buddy"> . . . </applet>

2) By specifying a NAME parameter with a <PARAM> tag. For example:

<APPLET CODEBASE=example/ CODE=Receiver.class WIDTH=450 HEIGHT=35> <PARAM NAME="name" value="old pal"> . . . </applet>

Page 21: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Applet receiver = null;String receiverName = nameField.getText(); //Get name to search for.receiver = getAppletContext().getApplet(receiverName);

if (receiver != null) { //Use the instanceof operator to make sure the applet //we found is a Receiver object. if (!(receiver instanceof Receiver)) { status.appendText("Found applet named " + receiverName + ", " + "but it's not a Receiver object.\n"); } else { status.appendText("Found applet named " + receiverName + ".\n" + " Sending message to it.\n"); //Cast the receiver to be a Receiver object //(instead of just an Applet object) so that the //compiler will let us call a Receiver method. ((Receiver)receiver).processRequestFrom(myName); } } . . .

Page 22: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Playing Sound

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.

Page 23: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Using the Applet Tag

• Like command line arguments for applets

• Customize applet operation

• User Configures Names

• Provide Default Values

• Parameter values are all strings

• Let applet interpret string

Page 24: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

<APPLET CODE=AppletButton.class CODEBASE=example WIDTH=350 HEIGHT=60> <PARAM NAME=windowClass VALUE=“BorderWindow”> <PARAM NAME=windowTitle VALUE="BorderLayout"> <PARAM NAME=buttonText VALUE="Click here to see a BorderLayout in action"> </APPLET>

Page 25: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

int requestedWidth = 0; . . . String windowWidthString = getParameter("WINDOWWIDTH"); if (windowWidthString != null) { try { requestedWidth = Integer.parseInt(windowWidthString); } catch (NumberFormatException e) { //Use default width. } }

Page 26: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

String windowClass; String buttonText; String windowTitle; int requestedWidth = 0; int requestedHeight = 0; . . . public void init() { windowClass = getParameter("WINDOWCLASS"); if (windowClass == null) { windowClass = "TestWindow"; }

buttonText = getParameter("BUTTONTEXT"); if (buttonText == null) { buttonText = "Click here to bring up a " + windowClass; }

windowTitle = getParameter("WINDOWTITLE"); if (windowTitle == null) { windowTitle = windowClass; }

String windowWidthString = getParameter("WINDOWWIDTH"); if (windowWidthString != null) { try { requestedWidth = Integer.parseInt(windowWidthString); } catch (NumberFormatException e) { //Use default width. } } ...

Page 27: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

Combining Applet Files

• If applet has more than one file, combine into zip archive

• jar tool and JAR format from java• jar cvf file.zip com/mycompany/myproject/*.class *.gif

(Solaris)

• jar cvf file.zip com\mycompany\myproject\*.class *.gif (Windows 95/NT)

Page 28: Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example

<APPLET CODE="AppletSubclass.class" ARCHIVE="file1, file2" WIDTH=anInt HEIGHT=anInt> </APPLET>