09 Apple Ts and Applications

download 09 Apple Ts and Applications

of 26

Transcript of 09 Apple Ts and Applications

  • 7/29/2019 09 Apple Ts and Applications

    1/26

    nabg

    Appletsand

    Applications

    nabg

    Application

    Applet

    HTML for applets class Applet

    Inevitable HelloWorld example

    More simple applet examples

    JApplet

    (Practical alternative to Applets Java Web Start)

    nabg

    Applets and Applications Application

    independent program

    full access to host machine normal file access (standard security constraints on file ownership)

    ability to create sockets (arbitrary network connections)

    (slightly restricted) access to environment variables

    GUI create Frame (or JFrame) object as principal window

    may have additional windows for dialogs, alerts etc

    nabg

    Applets and Applications

    Applet

    program embedded in web page and run by browser

    restricted access to machine on which it is run(restrictions can be varied by sophisticated browser)

    no access to local files

    can open network connection only to site from where appletwas itself loaded

    can access some details of enclosing web page

    GUI

    use part of browsers page window for main window

    nabg

    Applet

    Applets do have many restrictions

    but they were the feature that popularised Java

    downloadable executable content

    security policy easily enforced by browser environment

    lots more pretty GUI features than you could readilyobtain with just HTML+forms

    real computations, not just checks on data entry &trivial calculations as in J avascript

    nabg

    Internet

    Client machine Web servermachine

    Web browserprogram

    (J ava byteinterpreter,HTML, applet bytecodes)

    httpdweb serverprogram

    Screen with browser windowcontaining Applet subwindow

    J ava

    HTML

    Bytes

    Server fi lesystem

    /http_docs

  • 7/29/2019 09 Apple Ts and Applications

    2/26

    nabg

    Application

    Applet

    HTML for applets class Applet

    Inevitable HelloWorld example

    More simple applet examples

    JApplet

    (Practical alternative to Applets Java Web Start)

    nabg

    Applet -HTML

    HTML code on web page contains tag specifyingapplet (

  • 7/29/2019 09 Apple Ts and Applications

    3/26

    nabg

    HTML for Applets

    Applet demo

    See my applet

    Your browser is Java challenged, modernise!

    Text between and displayedif browser doesnt support applets.

    nabg

    HTML for Appletsoptions in

  • 7/29/2019 09 Apple Ts and Applications

    4/26

    nabg

    Parameters for applet

    you have a java challenged browser, modernise

    paramsplaced betweenandtags

    nabg

    Application

    Applet

    HTML for applets class Applet

    Inevitable HelloWorld example

    More simple applet examples

    JApplet

    (Practical alternative to Applets Java Web Start)

    nabg

    class Applet

    class MyApplet extends Applet/J Applet { ... }

    AnApplet is a

    Panel is a

    Container is a

    Component is an

    Object

    Or extends JAppletif you want the modern swing graphics

    nabg

    Application

    class MyApplication extends Frame{ ... }

    An application (with a GUI) is something

    that uses (or, sometimes, is) aFramewhich is a

    Windowis aContainer is a

    Component is an

    Object

    nabg

    Application

    More typicallypubl i c cl ass MyGui ext ends Fr ame/ J Fr ame

    {}

    publ i c cl ass MyAppl i cat i on {

    st ati c MyGui t heGUI ;

    publ i c stati c voi d mai n(Str i ng[] args) {

    theGUI = new MyGui () ;

    }

    nabg

    class Applet

    Because an Applet is a Component

    it is a basic GUI element in its own right

    it has a paint() method, a repaint(), an update(),...

    Because it is also a Container

    it can have subwindows, so can holdCanvases, Checkboxes, Buttons, ...

    And, because it is a Panel, it has adefined way of arranging subwindows

  • 7/29/2019 09 Apple Ts and Applications

    5/26

    nabg

    class Applet

    An Applet has its own unique functionality init() first method called when applet

    being started; typically does thingslike read parameters, load images, ...

    start() called after init() and each time userreturns to HTML page with applet;typical use -starting threads, ...

    stop() called each time user leaves HTMLpage; typical use - suspend threads

    destroy() free resources (doesnt Java do this? well,sometimes applet does have stuff to clean up)and kill threads

    Applet - execution control (these may be overridden in subclasses)nabg

    class Applet

    An Applet has its own unique functionality getAppletContext() returns an object which allows some

    communication with browser & HTML page

    getParameter(Stringname) returns value of parameter with name(or null)

    getCodeBase(), getDocumentBase()return URLs of page, etc

    showStatus(Stringmsg) puts message in status windowofbrowser

    Applet - access environment

    nabg

    class Applet

    An Applet has its own unique functionality getImage(URL src) arranges to load an image (eg a .gif file) that

    is to be displayed in (a subwindowof) Applet

    getAudioClip(URL src) arranges to load a sound file

    play(URL src) plays sound file

    Image not loaded until try to display, then may get delays. Loading an Audio allows finer control, can start sound clip, stop

    it etc; play() simply plays it, or does nothing if cannot load.

    Multimedia features figure prominently in toy applets.

    Applet - manipulate multimedia datanabg

    Application

    Applet

    HTML for applets

    class Applet

    Inevitable HelloWorld example

    More simple applet examples

    JApplet

    (Practical alternative to Applets Java Web Start)

    nabg

    The inevitable

    HelloWorldapplet

    nabg

  • 7/29/2019 09 Apple Ts and Applications

    6/26

    nabg

    HelloWorldapplet

    All it does is

    pick a color using argument

    draw in its subwindowwithin browser

    So,

    a specialised subclass of Applet

    has an init() method that reads parameter

    has a paint(Graphics g) method that draws

    accepts defaults (do nothing) for start(), stop(), ...

    nabg

    HTML file for Hello Applet

    Hello Applet

    See my Applet

    You are Java challenged!

    nabg

    class helloextends Applet

    import java.awt.*;

    import java.applet.*;

    public class hello extends Applet{

    Color c =Color.black;

    public void init() { ... }public void paint(Graphics g) { ... }

    }

    nabg

    class helloextends Applet

    public void init() {

    String colorval =getParameter("color");

    if(colorval ==null) return;

    if(colorval.equals("red")) c=Color.red;

    if(colorval.equals("blue")) c=Color.blue;

    }

    nabg

    class helloextends Applet

    public void paint(Graphics g) {

    g.setColor(c);

    g.drawOval(50, 60, 100, 150);

    g.fillOval(70, 110, 20, 20);

    g.fillOval(110, 110, 20, 20);

    g.drawArc(70, 170, 50, 15, 0, -180);

    }

    nabg

    create hello.html and hello.java

    javachello.java

    appletviewer hello.html (NetBeansdoes this totest applet)

    or

    communicator, open hello.html

    or

    mozilla, open hello.html

    Communicator (default browser onUnix) is quite old and has a numberof l imitations.Mozillacauses unpleasant colour fl ickerson Sun Blade workstations

  • 7/29/2019 09 Apple Ts and Applications

    7/26

    nabg

    Problems testing applets

    Remember supposed to be opening files acrosshttp style network.

    This sometimes causes problems when trying totest an applet and just using local files.

    Some operations dont work (browser appliessecurity restrictions so cannot get files).

    Tests with local files usually work better if useAppletViewer.

    nabg

    Applet constructor?

    Typical class constructor of class does all work to initialize it

    (so would expect a GUI class to do setup andinitialization in constructor)

    Typical Applet class (as in Suns examples) work is done in init() rather than constructor

    ?

    nabg

    Applet constructor has limitations

    Reason is that some GUI elements cannot beinitialized in constructor (most can)

    Some odd features about setting up Applet environment

    Environment not set right until constructor completed

    Some GUI elements require interrogation of

    environment and cannot be created properly from inconstructor

    (Only those needing an image to be loaded??)

    nabg

    NetBeansversion

    First chance to meet the GUI builder

    nabg

    As usual, new Projectnew Package

    New File/ Applet Form

    nabg

    Pick Applet Form

  • 7/29/2019 09 Apple Ts and Applications

    8/26

    nabg

    Form-editing view of applet class

    nabg

    Code-editing view of Applet class

    nabg

    GUI editing : form-page/code-page

    (This style is common, if you get to work withMicrosofts Visual Studio you will see verysimilar operation.Actually, Microsoft really lead the development ofvisual editors starting way back in the late 1980s.)

    Two views swap back and forth Point and click editor, adding visual components and

    setting their properties

    Code editor see the resulting code

    nabg

    Hello Applet NetBeansstyle

    Actually have now finished the GUI editing!

    (It isnt usually that simple.)

    This Applet has no subordinate GUI elements (no buttons,no text input fields etc etc)

    Still have to define the code to pick up the color parameterand to draw the little picture!

    Switch to text view.

    nabg

    Add some lines to init() suppliedby NetBeans

    NetBeanswill have generated some code in the init() function,add own code to read applet-paramsand set colour; add colourdata member

    nabg

    Add the paint function

    That little blue arrow?It is a tag that NetBeansadds; it means this functionoverrides the definition of the function in the base class

  • 7/29/2019 09 Apple Ts and Applications

    9/26

    nabg nabg

    nabg

    Generated HTML file

    Run file caused NetBeansto generate aHTML file that has request for embeddedapplet,then ran this with AppletViewer

    Generated file is in buildfolder,copy and edit it if need parameters

    nabg

    nabg

    HTML

    Applet HTML Page

    Generated by NetBeansIDE

    Need to add the paramtag specifying a colour

    nabg

    Edit the copy add params

  • 7/29/2019 09 Apple Ts and Applications

    10/26

    nabg

    and run again

    nabg

    NetBeansapplet outside of NetBeans

    Copy the generated .jar file

    dist/AppletDemo.jar

    Compose a HTML page

    nabg

    HTML

    My NetBeansHelloApplet HTML Page

    My Hello applet will appear below:

    nabg

    nabg

    HTML pages

    Usually, HTML page displaying an appletwill have lots of markup, content text, andmaybe pictures as well as the applet.

    AppletViewer shows only the applet.

    You have to view page in browser if youwant to see all the content.

    nabg

    Application

    Applet

    HTML for applets

    class Applet

    Inevitable HelloWorld example

    More simple applet examples

    JApplet

    (Practical alternative to Applets Java Web Start)

  • 7/29/2019 09 Apple Ts and Applications

    11/26

    nabg

    More Appletexamples

    nabg

    Horstmannsexample applets

    Following examples from Horstmann, Core Java

    chart applet

    bookmark applet

    nabg nabg

    HorstmannsChart Applet

    Illustration of use of

    Applet

    draw bar chart

    named columns

    relative heights defined by double values

    tags allow same applet todisplay different data on different pages

    could use in generated page with tags as output from some program

    Minor mods to use standard i/o rather than Horstmanns library

    Really nothing much more than the HelloWorld example

    nabg

    ...

    ...

    Chart.html

    nabg

    Chart.javaimport java.awt.*;

    import java.applet.*;

    import java.io.*;

    public class Chart extends Applet

    {

    public void init() { ... }

    public void paint(Graphics g) { ... }

    private double[ ] values;

    private String[ ] names;

    private String title;

    }

  • 7/29/2019 09 Apple Ts and Applications

    12/26

    nabg

    public void init()

    { intn = Integer.parseInt(getParameter("values").trim());

    values =new double[n];

    names =new String[n];title =getParameter("title");

    int i;

    for (i =0; i

  • 7/29/2019 09 Apple Ts and Applications

    13/26

    nabg nabg

    Horstmannsbookmark applet

    Illustrates communication with AppletContext

    request that AppletContextdisplay a different page(display is in frame, could have used a separatewindow)

    Multiple HTML files

    frameset using two frames

    contents for frames

    nabg

    Bookmark Applet

    Bookmark.java (HTML file that defines frameset with

    contents Left.html and Right.html)

    nabg

    A Bookmark Applet

    Double-click on one of the names in the list box. The corresponding webpage

    will be displayed in the frame on the right.

    ...

    Left.html (HTML file that contains and

    associated s)

    nabg

    Web pages will be displayed here.

    Double-click on one of the names in the list box to the left. The web page

    will be displayed here.

    Right.html (HTML file that contains initial

    filler for right hand frame)

    nabg

    import java.awt.*;

    import java.awt.event.*;import java.applet.*;

    import java.net.*;

    import java.io.*;

    public class Bookmark extends Applet implements ActionListener{

    public void init() { ... }

    public void actionPerformed(ActionEventevt) { ... }

    private List links =new List(10, false);

    }

    A List GUI element can respond to a double click byreporting anActionEvent

    something has to handle that event

    might as well be the Applet, no need for any other object

    Bookmark.java

  • 7/29/2019 09 Apple Ts and Applications

    14/26

    nabg

    public void init(){

    setLayout(new BorderLayout());

    add("Center", links);

    links.addActionListener(this);inti =1;

    String s;

    while ((s =getParameter("link_" +i)) !=null) { links.add(s); i++; }

    }

    public voidactionPerformed(ActionEventevt){

    String arg=evt.getActionCommand();

    try

    { AppletContextcontext =getAppletContext();

    URL u =new URL((String)arg);

    context.showDocument(u, "right");

    } catch(Exception e) { showStatus("Error " +e); }

    }

    nabg

    Horstmansbookmark applet

    Defined only

    init This created a java.awt.List with data from Applet parmaters

    actionPerformed This lets applet talk to applet-context (i.e. browser) asking for

    display of another page

    How did it get to paint the list? No paint() methoddefined!

    nabg

    Applet.paint()

    Applet is a Panel which is a Container

    Container has a default paint method

    For each component that I contain, tellcontained component to paint itself

    This Applet contains a java.awt.Listpr i vate Li s t l i nks = new L is t ( 10, fa l se) ;

    add(" Center", l i nks);

    nabg

    java.awt.List.paint()

    The java.awt.Listclass defines a paint method

    Use a scrollable pane, draw scrollbar if necessary

    Draw each entry (String) on a line in scrollable pane

    So didnt need to redefine paint in the applet itself,

    the default inherited methods do whatever isnecessary.

    nabg

    Chooser Applet

    Applet with interactive controls

    nabg

    Chooser Applet

    Most GUI interfaces, and many Applets,use standard controls that let user selectprocessing operations.

    Following simple applet illustrates some ofthese controls and also shows off more ofNetBeansGUI Builder

  • 7/29/2019 09 Apple Ts and Applications

    15/26

    nabg

    Chooser Applet

    Applet is to show Rectangle or Oval

    Top/left, width/height adjustable

    Applet is to have drawing area where shape displayed

    Control area Choice of Rectangle/Oval

    Labels and text fields for dimensions

    Action button

    nabg

    Rough view

    Drawing area

    showing a rectangle

    Controls in panel at bottom

    nabg

    GUI components

    This time Applet isnt simply a single panel usedto display data (as it has been in all previousexamples)

    As a Panel (a kind of Container) it can hold otherGUI components.

    Here, want it to hold

    A Canvas a region reserved for drawing data object A collection of text input fields (with associated labels)

    Fields for top, left, width, and height

    A button which will cause applet to change data anddisplay

    nabg

    GUI classes

    Need to use Standard GUI components

    Button

    Label

    TextField

    Choice (pop-up list offering Rectangle/Oval)

    Panel Customized GUI components

    MyCanvasextends Canvas

    Layout manager (arranges how components displayedin Applet)

    nabg

    GUI components

    Topic of next main lecture segment!

    For now Label

    Create Label object with String

    Place in GUI

    TextField Editable text automatically looks after all keyboard and

    mouse editing action

    Can ask a TextField for its current text when needed

    Button Generates action events

    nabg

    GUI components

    GUI components: Label, TextField, Button,and Choice

    Choice Pop-up list, lets you pick one out of a set of

    String values

    Create choice object

    Place in GUI

    Add option, add option, add option

  • 7/29/2019 09 Apple Ts and Applications

    16/26

    nabg

    Customized GUI component

    Canvas

    Reserve an area of GUI for display of application data

    paint() uhm, paint what?

    Have to create a subclass of Canvas to haveanything useful!

    Class MyCanvasextendsCanvas

    Has link to data object

    paint() function can arrange for painting of data object

    nabg

    BorderLayout

    Will be dealing with layout managersshortly.

    BorderLayout is convenient for simpleapplications Divides Applet (or other container) into upto

    five regions (dont have to use them all) Center, North, East, South, West

    Each region can hold one other component Canvas, Button, Label

    nabg

    BorderLayout

    NORTH

    SOUTH

    WestEast

    Center

    nabg

    Extra panels

    BorderLayoutallows for one component in each of itsregions

    We need several Label and text-field for top

    Label and text-field for left

    Choice Action button

    Have to use extra Panel objects Place Panel in south region

    Add labels and text-fields etc to this panel

    nabg

    BorderLayoutas used

    NORTH holds a title (Label)

    SOUTH panel holding labels, textfields, button

    Center MyCanvasdisplaying rectangle oroval

    nabg

    Event listening

    Button will generate ActionEvents

    Applet will listen for the ActionEvent Handle it by changing data and arranging for

    update of display

    Applet creates the button in its init()method, will add itself as the action-listeneronce button created.

  • 7/29/2019 09 Apple Ts and Applications

    17/26

    nabg

    Event listening the usual

    GUI interface

    Component that generates events (Button)

    Defined class that will implement appropriatelistener so that it can handle the event (Appletclass will implement ActionListener)

    Initialization code will link listener to event source

    You should be getting the idea of event listeningby now

    nabg

    Classes

    Data

    Owns some Shape

    Does Gets told to draw its shape or change its shape

    MyCanvas

    GUI component occupies space in GUI where drawdata

    Simply owns link to data and passes on paint requests

    ChooserApplet

    nabg

    MyCanvas

    public class MyCanvasextends Canvas {

    private Data myData;

    public MyCanvas(Datad) {

    myData=d;

    }

    public void paint(Graphicsg) { myData.paint(g); }

    }

    nabg

    Datapublic class Data {private Rectangle myShape;private booleanoval;public Data() {

    myShape=new Rectangle(40,80,100,50);oval =false;

    }public void makeRectangle(int top, int left, int width, intheight) {

    myShape=new Rectangle(top, left, width, height);oval =false;

    }public void makeOval(int top, int left, intwidth, int height) {

    myShape=new Rectangle(top, left, width, height);

    oval =true;}public voidpaint(Graphicsg) {

    if(oval)g.fillOval(myShape.y, myShape.x, myShape.width, myShape.height);

    elseg.fillRect(myShape.y, myShape.x, myShape.width, myShape.height);

    }

    nabg

    NetBeans

    New Project

    New Package

    New Java class MyCanvas

    New Java class Data

    New Applet Form ChooserApplet

    nabg

    Applet

    Create the applet class

    In form view, click the outline and selectsetLayout,choose BorderLayout

  • 7/29/2019 09 Apple Ts and Applications

    18/26

    nabg nabg

    Add parts

    Label at top

    Palette/AWT

    Drag Label into top of outlined applet panel

    nabg

    Fix up properties

    Select label

    Go to properties subwindow Change Font (larger size, )

    Change Text (Chooser Applet)

    Change Alignment (center)

    Also change Name of variable

    nabg

    South

    From AWT add Panel to South

    Then add to the panel:

    Pair (Label, TextField) for each of inputs

    Fix variable names to make them meaningful

    nabg nabg

    Adding code

    Properties box of component also has a codetab; Can specify extra code to be inserted before code that

    adds component Can specify different specialized code for adding a

    component Can specify extra code to be inserted after code that

    adds component

    For Choicecomponent Have to add the Choice object Then in Post creation codeneed to add the Strings

  • 7/29/2019 09 Apple Ts and Applications

    19/26

    nabg

    Added Choice to PanelChanged name to shapeChoiceUsed properties panel to

    set font etc;Then switched to Code

    section of properties

    Added code

    nabg

    ActionButton

    Similarly add Button

    But now want something special a listenerwill be attached to this button

    It is going to be the Applet

    Need extra code something other thanroutine; addActionListener(this)

    nabg

    Adding code

    Here need extra code after

    Add actionListener

    Specify this (i.e. the applet) as the action listener

    Note will result in code that is erroneous we

    havent yet specified that the applet is toimplement ActionListener interface; will fixshortly

    nabg

    nabg

    MyCanvas

    Main central region of Applet is to show aMyCanvaswhere will draw the data.

    AWT palette doesnt have MyCanvas

    AWT palette does have Canvas! Add a Canvas

    Use code properties to customize creation code

    nabg

  • 7/29/2019 09 Apple Ts and Applications

    20/26

    nabg

    Switch to code view

    Generated code includes an initComponentsfunction

    Shown collapsed, with a do not Edit warning

    Open collapsed view

    See errors

    addActionListener(this) when ChooserApplet is notan ActionListener

    new MyCanvas(theData) when theDatanot defined

    nabg

    nabg

    Fix-ups

    Add implements ActionListener to class

    Fix imports

    Then tell NetBeansto implement all declaredmethods

    Get an empty actionPerformed() function added Declare a private data member of class Data

    and create instance in init() function (beforecall to initComponents())

    nabg

    nabg

    Implement actionPerformed

    When Button pressed

    Check that one of items in choice has been chosen If none chosen, do nothing

    Read data values from each of TextFieldsand convertto integers

    If any input conversion errors, do nothing

    Invoke operation on data object to set new shape anddimensions

    Request update of My Canvaspart of display

    nabg

    Action performed

  • 7/29/2019 09 Apple Ts and Applications

    21/26

    nabg

    Run the Applet

    Run file ChooserApplet

    Will need to resize appletviewer window

    nabg

    nabg

    Event listening again

    So, typical event listening application

    Button in GUI is source of ActionEventevents

    ChooserApplet is a listener for action events

    implements ActionListener

    Listener object registered with event sourcedoItButton.addActionListener(this);

    actionPerformed() function does some workwhen event occurs

    nabg

    Other events?

    Choice

    Potentially source of ItemEvents Each time you change a selection you get Deselected then

    Selected events

    TextField

    Potentially source of TextEvents Each change to one of number fields will result in event

    NOT listening for either TextEventsor ItemEvents

    nabg

    Usually only monitor action buttons

    Dont need to know that user is changing the Itemselection

    Dont need to know details of each change madeto text input fields

    Leave these controls to look after themselveswhile user is entering data

    Wait for user to complete input; user will thenactivate action button.

    nabg

    NetBeansauto-generation ofevent handling code

  • 7/29/2019 09 Apple Ts and Applications

    22/26

    nabg

    Event handling

    Normal

    Make one of your classes implementappropriate listener

    Add instance of class as listener to event source

    NetBeanshas an option that automates partof code but uses a different approach

    nabg

    Chooser2 applet

    Simplified version of Chooser

    Ive just added a Choice and an Button to panel

    Ive selected Events from the properties panelassociated with the Button

    Picked Action events

    Dialog (not very clear) is asking me to enter a name fora function that will be added to enclosing applet thatwill handle the action-event

    nabg nabg

    Generated code 1

    nabg

    How does handleButton() get called?Magic!

    Well actually, look inside theinitComponentsand all will be revealed(sort of)

    nabg

  • 7/29/2019 09 Apple Ts and Applications

    23/26

    nabg

    Anonymous inner class code --- yuk

    doIt.setLabel("Do it");

    doIt.addActionListener(newjava.awt.event.ActionListener() {

    public void actionPerformed(

    java.awt.event.ActionEventevt) {

    handleButton(evt);

    }

    });

    nabg

    Inner class code

    That stuff

    Defines a new class with an actionPerformedmethod

    This actionPerformedmethod calls the handleButtonfunction in the enclosing Applet class

    Creates an instance of this class and attaches it to thebutton

    Depends on obscure properties of inner classes inJava

    nabg

    Auto-code

    Personally, I dont like such code

    I find inner classes and their conventions anunnecessary and confusing addition to Java

    This approach forces the applet to be thelistener for the button

    nabg

    Model-View-Control

    These applications have three aspects Model (Data)

    The data being manipulated

    View The GUI views of application data, input fields for use by

    user

    Control Monitor the inputs (listen for those events that really need to

    handle)

    Read and validate data inputs

    Invoke processing operation

    nabg

    Model-View-Control : 3 separateaspects

    These are different aspects of application

    Best handled by three separate classes (or, usually,clusters of classes) Model main class owning all application data and

    performing application actions View main GUI class Control best placed in another class

    Main program creates model, GUI, and controlobject and links them up

    nabg

    NetBeansauto-coder: View=Control

    Auto-code approach forces Applet to beboth view and control in application

    Maybe OK in simple cases

    Not a good idea in more advanced applications

  • 7/29/2019 09 Apple Ts and Applications

    24/26

    nabg

    NetBeansGUI editing

    Is it worth it?

    nabg

    NetBeansGUI editing

    Is it worth it?

    For simple examples like this

    No It is easier to write the code for the GUI than fiddle

    with all those dialogs especially the dialogs foradding custom code like Post create etc

    nabg

    NetBeansGUI editing : for complexGUIs

    With more complex GUI interfaces, the GUIeditor approach is definitely advantageous.

    GUI editor may not help much (may even hinder)development of simple applications but use itanyway to see how it works

    GUI editor very useful later with complex GUIs

    nabg

    Applet restrictions

    nabg

    Sandbox environment

    Java programs run with security managerobjects

    all calls to functions are interpreted, so haveopportunity to hook in extra checking at time of call;

    classes get tagged with information (class loader &security manger) when loaded; if there is a securitymanager, then this will be used to vet function calls;

    security manager loaded for applets is by default veryrestrictive

    nabg

    No peeking by applets

    Applets cannot

    access directories or files on machine that hostsbrowser

    cannot read pixels from the screen

    cannot open socket connections to machineother than one from which applet downloaded

  • 7/29/2019 09 Apple Ts and Applications

    25/26

    nabg

    Easing the restrictions

    Restrictions prevent things like a simplespreadsheet applet (you couldnt store your data)

    So more elaborate security system introduced.

    Applets get security certificates (mechanism thatallows browser to verify that applet really is fromsource specified)

    Applets that have such security certificates cannegotiate with user (via dialogs) can applet have permission to access files?

    can applet open socket to xxx.yyy.zzz.aaa

    nabg

    Permissions for applets

    Allows applets to be used for more thansimple demos and games

    nabg

    JApplet

    If you want to use swing classes (fancythings like JTable) then you must use

    JApplet rather than Applet

    One problem! threads and swing!

    nabg

    Swing thread issue & JApplet

    Swing library is unchecked single threadedcode unchecked means no locks

    Swing code should only be executed byevent handling thread

    init() function of Applet (JApplet) is notexecuted by event handling thread

    nabg

    invokeLater etc

    Strictly, you cannot build a JAppletinterface in an init()method that adds JTextFields, JButtonsetc

    Instead you have to use more elaborate code that createstasks that will be invoked later by the event handlingthread

    Most simple JAppletexamples dont seem to do this they work

    almost always

    (if you create the display in the constructor they might alwayswork provided you dont use images etc)

    nabg

    JApplet you have been warned

    Cannot rely on simple JApplet interfacebuilding to always work

    See Sun JAppletexamples for complexcode that does interface building correctly

  • 7/29/2019 09 Apple Ts and Applications

    26/26

    nabg

    NetBeansand JApplets

    Naturally, NetBeanscan generate the messyJAppletset up code

    So OK, to build swing style applets(JApplets) if using NetBeans

    nabg

    Applets?WebStart?

    nabg

    Applets

    Not used much in practice

    Permission system improved scope

    But still rather impractical hassles with JVMsin browsers, slow download times etc

    Actually, Ive noticed usage increasing in last couple of years.Numerous sites (most of newspapers for example) appear to loadan Applet that tracks your usage and measures download times, sendingthe data back to web site this Applet doesnt have any GUI.SOLS, WebCT Vista applet dependent.

    nabg

    WebStart

    Alternative technology for downloadableexecutables

    Code (.class files, .jar archives) cached on clientmachine in directory managed by WebStartsystem

    Link in HTML page to WebStartprogram

    start a JVM on client machine first task check that cached version of code is up to date, if

    necessary download revised classes

    run Java program separately from browser

    nabg

    Webstart -2

    Certification etc can verify that really runningthe correct code, not something interposed byhacker

    Restrictions can define access rights for awebstartprogram

    Full GUI, unrestricted by browser

    Combines applet advantage of downloadable secure code

    application advantages