APPLET - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

APPLET

Description:

... VALUE='Calculate' onClick='compute(this.form) ... on form element or link onClick ... 'button' VALUE='Press me' ONCLICK='testit(this.form)' /FORM ... – PowerPoint PPT presentation

Number of Views:78
Avg rating:3.0/5.0
Slides: 25
Provided by: qian2
Learn more at: https://www.cse.scu.edu
Category:

less

Transcript and Presenter's Notes

Title: APPLET


1
APPLET
  • Loaded into a java-enabled program (Netscape,
    Applet Viewer)
  • Applet lifecycle (methods overriden from Applet
    class)
  • init, start, stop, destroy
  • Loading an applet
  • an instance of the applets controlling class
    (Applet subclass) created
  • applet initializes itself
  • applet starts running
  • Leaving and returning to applet page
  • when page is left, applet stops
  • upon page return, applet starts
  • Applet reloading/unloading
  • applet performs final cleanup, before reloading
  • Browser quitting - (applet stops, performs final
    cleanup)

2
APPLET - continued
  • simple.html
  • lthtmlgtltbodygt
  • ltapplet codebase http//www.scudc.scu.edu/user
    name/classes codeSimple.class width150
    height25gt
  • lt/appletgtlt/bodygtlt/htmlgt
  • Load page into netscape, or use appletviewer
  • appletviewer simple.html
  • Example Simple.java

3
Applet life cycle
  • init()
  • initialize applet when loaded (or reloaded)
  • put in one-time initialization info (like a
    constructor)
  • start()
  • start applet execution, called when loaded and
    when page revisited
  • usually overriden, performs actual applet work
  • stop()
  • stop applet execution, called when page left or
    browser quit
  • destroy()
  • perform final cleanup in prep for unloading

4
Other applet methods
  • Drawing methods
  • paint(Graphics g)
  • basic display method
  • override to draw app-specific representation in a
    browser page
  • update()
  • use to improve performance of display
  • Event handling
  • applets inherit event-handling methods from
    Component class (based on awt architecture)
  • action()
  • mouseDown()
  • handleEvent()
  • etc.

5
Design GUI Using AWT
  • Basic idea You can create a panel on the screen
    and put your GUI objects in.
  • Applet extends Panel (which is a Container), so
    it can contain other GUI components. Inherits
    default layout manager, event handling
  • GUI components Panel, Button, Text Area, List,
    Label,etc.
  • Things to learn
  • Layout How to put things to where you want.
  • Event handling How do I know the user has
    clicked a button, or selected an item in a list,
    and what can I do at that point.
  • Our learning steps
  • Basic layout Border Layout, Grid Layout
  • Event handling

6
Other applet methods
  • Typical UI components
  • Buttons (java.awt.Button)
  • Checkboxes(java.awt.Checkbox)
  • Simple Text (java.awt.TextField)
  • Larger text, editing areas (java.awt.TextArea)
  • Labels (java.awt.List)
  • Popup lists (java.awt.Choice)
  • Sliders, scrollbars (java.awt.Scrollbar)
  • Drawing areas (java.awt.Canvas)
  • Menus(java.awt.Menu,java.awt.MenuItem,java.awt.Che
    ckboxMenuItem)
  • Containers (java.awt.Panel, java.awt.Window)
  • Adding GUI component methods (Applet extends
    Container)
  • add, remove, setLayout
  • Example ScrollingSimple.java

7
Another Example Scribble
  • import java.applet.
  • import java.awt.
  • public class Scribble extends Applet
  • private int last_x 0
  • private int last_y 0
  • private Color current_color Color.black
  • private Button clear_button
  • private Choice color_choices
  • // Called to initialize the applet.
  • public void init()
  • // Set the background color
  • this.setBackground(Color.white)
  • // Create a button and add it to the applet.
  • // Also, set the button's colors
  • clear_button new Button("Clear")
  • clear_button.setForeground(Color.black)
  • clear_button.setBackground(Color.lightGray)
  • this.add(clear_button)
  • // Create a menu of colors and add it to the
    applet.
  • // Also set the menus's colors and add a label.
  • color_choices new Choice()
  • color_choices.addItem("black")
  • color_choices.addItem("red")
  • color_choices.addItem("yellow")
  • color_choices.addItem("green")
  • color_choices.setForeground(Color.black)
  • color_choices.setBackground(Color.lightGray)
  • this.add(new Label("Color "))
  • this.add(color_choices)
  • // Called when the user clicks the mouse to
  • // start a scribble
  • public boolean mouseDown(Event e, int x, int y)
  • last_x x last_y y
  • return true

8
Scribble (cont.)
  • // Called when the user scribbles with the mouse
    button down
  • public boolean mouseDrag(Event e, int x, int y)
  • Graphics g this.getGraphics()
  • g.setColor(current_color)
  • g.drawLine(last_x, last_y, x, y)
  • last_x x
  • last_y y
  • return true
  • // Called when the user clicks the button or
    chooses a color
  • public boolean action(Event event, Object arg)
  • // If the Clear button was clicked on, handle
    it.
  • if (event.target clear_button)
  • Graphics g this.getGraphics()
  • Rectangle r this.bounds()
  • g.setColor(this.getBackground())
  • g.fillRect(r.x, r.y, r.width,
    r.height)
  • return true
  • // Otherwise if a color was chosen, handle that
  • else if (event.target color_choices)
  • String colorname (String) arg
  • if (arg.equals("black")) current_color
    Color.black
  • else if (arg.equals("red"))
    current_color Color.red
  • else if (arg.equals("yellow"))
    current_color Color.yellow
  • else if (arg.equals("green"))
    current_color Color.green
  • return true
  • // Otherwise, let the superclass handle it.
  • else return super.action(event, arg)

9
JavaScript
  • Where to find info http//home.netscape.com/eng/m
    ozilla/Gold/handbook/javascript/index.html
  • Processing data before it is submitted to the
    server CGI program
  • check inputs, mouse clicks, etc without network
    transmission
  • Using JavaScript in HTML
  • As statements and functions using the SCRIPT tag.
  • As event handlers using HTML tags.
  • The Script Tag
  • ltSCRIPTgt
  • JavaScript statements...
  • lt/SCRIPTgt
  • As event handler
  • ltTAG eventHandler"JavaScript Code"gt
  • Example
  • ltINPUT TYPE"button" VALUE"Calculate"
    onClick"compute(this.form)"gt

10
JavaScript vs. Java
  • JavaScript
  • Interpreted by client - not compiled
  • Object-based. No classes or inheritancebuilt-in,
    extensible objects of simple types (numeric,
    Boolean, string)
  • Integrated with / embedded in HTML
  • Do not declare variables' datatypes (loose
    typing)
  • Dynamic binding object references checked at
    run-time
  • Secure cannot write to hard disk
  • Java
  • Compiled on server before execution onclient
  • Object-oriented. Programs consist ofobject
    classes, with inheritance, etc.
  • Applets distinct from HTML (accessed
  • from HTML pages)
  • Must declare variables' datatypes (strong typing)
  • Static binding object references must exist at
    compile-time
  • Secure cannot write to hard disk

11
JavaScript Functions
  • Example 2 (defining functions)
  • ltHEADgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • function square(i) document.write("The call
    passed ", i ," to the function.")return i i
  • document.write(Result ",square(5),.)
  • lt/SCRIPTgt lt/HEADgt ltBODYgt
  • ltBRgt
  • All done.
  • lt/BODYgt
  • Displays to viewer
  • The call passed 5 to the function. Result 25.
  • All done.
  • Example 1
  • ltHTMLgt
  • ltHEADgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • document.write("Hello net.")
  • lt/SCRIPTgt
  • lt/HEADgt
  • ltBODYgt
  • That's all, folks.
  • lt/BODYgt
  • lt/HTMLgt
  • Displays to viewer
  • Hello net. That's all folks.

12
JavaScript Functions
  • ltHEADgtltSCRIPTgt
  • function bar() document.write("ltHR ALIGN'left
    WIDTH25gt")
  • function output(head, level, string)
  • document.write("ltH" level "gt" head
    "lt/H" level "gtltPgt" string)
  • lt/SCRIPTgtlt/HEADgt
  • ltBODYgtltSCRIPTgt
  • document.write(bar(),output("Make Me Big",3,"Make
    me ordinary."))
  • lt/SCRIPTgtltPgtThanks.lt/BODYgt
  • Make Me Big
  • Make me ordinary.undefinedundefined
  • Thanks.

13
Loading scripts
  • Scripts placed within SCRIPT tags are evaluated
    after page loads.
  • Functions are stored, not executed until called.
  • Should place functions in head (since head is
    loaded first), ensures functions defined before
    called.
  • some old browsers dont know how to handle
    Javascript and may show script contents, hide
    them in comment tag to avoid display ltscriptgt lt!
    -- hide script from old browser function
    square(i) document.write("The call passed ",
    i ," to the function.") return i i
  • document.write(Result ",square(5),.)
  • //end hiding from old browsers --gt lt/SCRIPTgt

14
Event Handling
can be any javascript statements, separate with
  • General formatltTAG eventHandler"JavaScript
    Code"gt E.g.ltINPUT TYPE"button"
    VALUE"Calculate" onClick"compute(this.form)"
  • "this" refers to the current object (button) and
    "this.form" refers to the form containing the
    object.
  • Events and event handlers
  • Event Occurs when
    Event Handler
  • blur User removes input focus from
    form element onBlur
  • click User clicks on form element or
    link onClick
  • change User changes value of text,
    textarea, or select element onChange
  • focus User gives form element input
    focus onFocus
  • load User loads the page in the
    Navigator onLoad
  • mouseover User moves mouse pointer over a
    link or anchor onMouseOver
  • select User selects form element's input
    field onSelect
  • submit User submits a form onSubmit
  • unload User exits the page onUnload

15
Event Handling (continued)
  • Usage event tags
  • Focus, Blur, Change events text fields,
    textareas, and selections
  • Click events buttons, radio buttons, checkboxes,
    submit buttons, reset buttons, links
  • Select events text fields, textareas
  • MouseOver event links
  • Event handlers are functions (user defined or
    predefined). Those functions can be called as
    ordinary functions.

16
JavaScript Example
  • ltHEADgtltSCRIPT LANGUAGE"JavaScript"gt
  • function compute(form)
  • if (confirm("Are you sure?"))
  • form.result.value eval(form.expr.value)
  • else
  • alert("Please come back again.")
  • lt/SCRIPTgtlt/HEADgt
  • ltBODYgtltFORMgt
  • Enter an expression
  • ltINPUT TYPE"text" NAME"expr" SIZE15 gt
  • ltINPUT TYPE"button" VALUE"Calculate
    ONCLICK"compute(this.form)"gt
  • ltBRgt
  • Result
  • ltINPUT TYPE"text" NAME"result" SIZE15 gt
  • lt/FORMgtlt/BODYgt
  • Enter an expression
  • Result

Calculate
type 35
17
JavaScript Example (conti)
  • ltHEADgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • lt!--- hide script from old browsers
  • function checkNum(str, min, max)
  • if (str "")
  • alert("Enter a num in the field, pls.")
  • return false
  • for (var i 0 i lt str.length i)
  • var ch str.substring(i, i 1)
  • if (ch lt "0" ch gt "9")
  • alert("Try a number, please.")
  • return false
  • var val parseInt(str, 10)
  • if ((val lt min) (val gt max))
  • alert("Try a number from 1 to 10.")
  • return false
  • return true
  • function thanks()
  • alert("Thanks for your input.")
  • // end hiding from old browsers --gt
  • lt/SCRIPTgt
  • lt/HEADgt
  • ltBODYgt
  • ltFORM NAME"ex5"gt
  • Please enter a small number, then click outside
    the field
  • ltINPUT NAME"num" onChange"if
    (!checkNum(this.value, 1, 10))
  • this.focus()this.select() else
    thanks()"gt
  • lt/FORMgt
  • lt/BODYgt

18
Language Compoments
  • JavaScript is a loosly typed language
  • You can do
  • var answer 42
  • answer "Hello World!"
  • Variable names start with and contain letters or
    "_", and also contain 0 thru 9.. They are
    case-sensitive
  • To declare a local variablevar x 0To
    declare global variablex some value // This
    can be in or outside functions.
  • Integers leading 0 is octal and leading 0X means
    hex.
  • Floating point Examples 3.1415, -3.1E12,
    .1e12, or 2E-12
  • Boolean values true and false.
  • String literals can be quoted by single or double
    quotes
  • String literals can contain control charaters
    \b, \f, \n, \r, and \t.
  • You can use \ to escape charactersE.g. "He said
    \"Hello\""
  • Operators and expressions are very similar to Java

19
JavaScript Object Model
  • A JavaScript object has properties.Use
    objname.propertyname to access a property.
  • You can define a property by assign it a value,
    e.g.myCar.make "Ford"myCar.model
    "Mustang"myCar.year 69
  • To create an object 1. write a function which
    creates properties.2. use new to create the
    objectExamplefucntion car(make, model, year)
    this.make make this.model model
    this.year year car1 new car("Ford",
    "Tempo",90)
  • You can add more properties to an object after it
    is created. E.g.car1.color "Red"// This adds
    property color to car1// But this does not
    affect any other // object created by car( )
  • You can refer to a property using the array
    notation e.g. car1"make"
  • Example of using array notation
  • function show_props(obj, obj_name)
  • var result ""
  • for (var i in obj) //i takes each prop name
  • result obj_name "." i " "
    obji "\n"
  • return result
  • What will we have if we do
  • document.write(show_props(car1, "car1")

20
Functions, Methods, and Built-ins
  • Function arguments can be strings, numbers, as
    well as objects.
  • You can refer to the arguments of a function
    (within the function) usingltfunctionnamegt.argumen
    tiAnd the number of arguments can be found by
    using ltfunctionnamegt.arguments.length
  • A method of an object is defined by associating a
    function with the object using the following
    syntaxobject.methodname function_nameThen
    you can call the method usingobject.methodname(p
    arams)
  • Built-in functions
  • eval(String x) // x is an expression string.
    eval // evaluates the expression and // return
    the result
  • // if x contains JS statements, // will
    execute the statements
  • ParseInt(String x, int base)convert x into
    integer using the base. return NaN if x is not a
    number.
  • ParseFloat(String x)convert x to float. return
    NaN if fails.
  • Control Statements if .. else, for, while,
    break, continue

21
Navigator Object Hierarchy
  • window
  • --parent, frames, self, top
  • --location
  • --history
  • --document
  • --forms
  • elements (text fields, textarea,
    checkbox, password
  • radio, select,
    button, submit, reset)
  • --links
  • --anchors

22
Navigator Objects (conti)
  • Key Navigator objects
  • The document object document.write() (or
    writeln()) -- write HTML text into the page
  • -- has onLoad and onUnload event handler.
  • The form object
  • A form can be referenced using its name if name
    defined by NAME attribute.
  • Forms of a document are stored in an array so
    they can be referenced by document.forms0
    ordocument.forms1 etc.
  • The window object
  • open and close Opens and closes a browser window
  • alert Pops up an alert dialog box
  • confirm Pops up confirmation dialog
  • frames0, frames1 frames in frameset.

23
  • ltHEADgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • function testit(form)
  • if (form.thename.value.length 0)
    alert("Please enter a name!")
  • else
  • if (form.likeit.selectedIndex
    0)
  • form.result.value "Glad you
    like it " form.thename.value
  • else
  • form.result.value "Sorry you
    do not like it " form.thename.value
  • lt/SCRIPTgtlt/HEADgtltBODYgtltFORMgt
  • Enter your name ltINPUT TYPE"text"
    NAME"thename" SIZE15 gtltBRgt
  • Do you like this page? ltSELECT NAME"likeit"gt
  • ltOPTIONgt YES ltOPTIONgt NO lt/SELECTgt
  • ltINPUT TYPE"button" VALUE"Press me"
    ONCLICK"testit(this.form)"gt
  • ltBRgt
  • Reply ltINPUT TYPE"text" NAME"result" SIZE30 gt
  • lt/FORMgtlt/BODYgt

24
ltHEADgtltSCRIPT LANGUAGE"JavaScript"gt function
testit(form) if (form.thename.value.leng
th 0) alert("Please enter a
name!") else
msgWindowwindow.open("","displayWindow","menubar
yes") msgWindow.document.write("ltHTMLgt")
if (form.likeit.selectedIndex 0)
msgWindow.document.write ("ltbodygtGlad
you like it " form.thename.value
lt/bodygtlt/htmlgt") else
msgWindow.document.write ("ltbodygtSorry you do not
like it " form.thename.value
"lt/bodygtlt/htmlgt") lt/SCRIPTgtlt/HEADgt ltBO
DYgtltFORMgt Enter your name ltINPUT TYPE"text"
NAME"thename" SIZE15 gtltBRgt Do you like this
page? ltSELECT NAME"likeit"gt ltOPTIONgt YES
ltOPTIONgt NO lt/SELECTgt ltINPUT TYPE"button"
VALUE"Press me" ONCLICK"testit(this.form)"gt lt/FO
RMgtlt/BODYgt
Write a Comment
User Comments (0)
About PowerShow.com