CS 1312 - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

CS 1312

Description:

And we have no idea nor do we want to care what platform a web surfer might be ... s = 'ooooh, big teeth!'; else if(nose.contains(p)) s = 'keen sense of smell' ... – PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 41
Provided by: BillL161
Category:
Tags: ooooh

less

Transcript and Presenter's Notes

Title: CS 1312


1
CS 1312
  • Introduction to
  • Object Oriented Programming
  • Lecture 27
  • April 24, 2001
  • Applets

2
Why Care about Applets?
  • Enable us to run java code embedded in a web page
  • Java is ideal since it is platform independent
  • And we have no idea nor do we want to care what
    platform a web surfer might be using
  • Allow use to make more powerful web pages
  • Allow us to serve a program to a user, but have
    them run it locally on their machine
  • Takes a major burden off us the server we
    simply serve (ie. transfer the file) the bytecode
  • Puts onus on user the client - to supply
    computing power to run the java code (imagine
    perhaps a game someone would want to run for
    hours.)
  • YOUR RESUME!

3
Limitations of Applets Why?
  • Applets are loaded from a remote site (web
    server, ex. ESPN web server)
  • Applets are designed to execute on a clients
    machine (ex. on a web surfer John Q. Publics
    Sony laptop running Windows 2000)
  • Security and trust are vital
  • Certain restrictions apply
  • Applets run inside a sandbox
  • Applet security manager protects the user

4
Some Limitations Capabilities of Applets
  • Cannot be used to spy on the clients
    machine(with minor exceptions)
  • Cannot alter a users system
  • Can show images
  • Can play sounds
  • Can get input from the user mouseclicks,
    keystrokes
  • Can send user input back to the host if desired
  • Can perform sophisticated calculations(dont let
    the app-let name fool you)

5
More Applet Restriction Details
  • Can never run any client executable
  • Cannot communicate with any host other than the
    server from which it came originating host
  • Cannot read or write to the clients file system
  • Can find out only limited info about the client
    machine
  • Java version in use
  • Name and version of OS running
  • Characters used as file and line separators
  • Client language (English) locale (Eastern US)
  • Client currency (US dollar)
  • Windows popped up by an applet carry a warning msg

6
Security Summary
  • Code is interpreted by the JVM and not executed
    directly
  • The security manager checks sensitive operations
    in the Java run-time library
  • Applets can contain a signature to identify their
    origin

7
Applet Creation
  • Use Swing extend the class javax.swing.JApplet
  • Use the AWT extend the class java.awt.AppletWe
    will focus on the newer library, Swing, and its
    applet class, JAppletJust as we have seen with
    a JFrame, if we attach components, we attach them
    to the containers content pane in this case to
    the JApplets content pane.Most, if not all, of
    what weve learned about Swing so far, is still
    applicable to JApplets!

8
What does the Browser do for us?
  • Instantiates the applet class we create
  • Runs several methods automatically
  • init()
  • start()
  • paint() / paintComponent()
  • stop()
  • destroy()
  • Those methods are exactly the ones we may need to
    override to have the applet behave as we wish
  • Sets up a layout manager instance and associates
    it with our content pane.

9
Applet Anatomy 101
  • We may want to override some of these
  • init()
  • instantiate GUI components
  • Register them with listeners
  • Add components to applet
  • Simple AWT - add components to Applet directly
  • Swing - getContentPane of JApplet and add to it
  • start()
  • Called automatically after init
  • Called anytime a user returns to the page
    containing the applet
  • Typical use reactivation of a thread
  • stop()
  • Override if you want to stop time-consuming
    activity when a user is off the page (animation,
    audio, threads)
  • Typical use - suspend a thread, suspend playing
    of audio

10
Anatomy of an Applet (cont.)
  • destroy()
  • called automatically when browser shuts down
  • typically do not need to override
  • AWT paint() or Swing paint() or
    paintComponent()
  • used to display graphics
  • called in special ways
  • Automatically called by browser
  • User can invoke by calling repaint()
  • update()
  • Is actually what repaint calls
  • Common to override under AWT style to reduce
    flicker
  • Usually not necessary to override when using
    Swing

11
Characteristics of Applets
  • Sometimes Graphical focus on paint method, use
    Graphics class for drawing
  • Usually GUI major focus on init method to set
    up GUI components
  • Instantiate them
  • Add them to the contentPane of the JApplet
  • Typically also event driven, so register them
    with listeners

12
Trivial Applet HelloApplet.java
  • import javax.swing.JApplet
  • import java.awt.
  • public class HelloApplet extends JApplet
  • // paint can be used to draw an applet
  • public void paint(Graphics g)
  • g.drawString("Hello World", 25, 50)
  • // paint
  • // HelloApplet

NoteThis applet is non-GUI and inherits from the
Swing applet class, JApplet
13
A Trivial Applet how do I run it?
  • You should use JDKs appletviewer program
  • Applets do not run naked
  • You need an HTML file to drive the applet
  • Its that HTML file that you run via the
    appletviewer!
  • appletviewer somePage.html

14
HelloApplet.HTML
  • ltHTMLgtltHEADgtlt/HEADgt
  • ltBODYgt
  • ltAPPLET codeHelloApplet.class
  • WIDTH100
  • HEIGHT100gt Any text placed here shows
    in
  • non-Java enabled browsers
  • lt/APPLETgt
  • lt/BODYgt
  • lt/HTMLgt

Note Where the actual applet appears depends on
the placement of the applet tag amongst the rest
of the HTML it is much like using an image tag.
15
Steps to compile and run an applet
  • Create applet source file
  • emacs HelloApplet.java
  • Create HTML source file
  • emacs HelloApplet.html
  • Compile the java source, creating class file
  • javac HelloApplet.java
  • Load the html file
  • appletviewer HelloApplet.html

Note the appletviewer is included with the
JDK/SDK. Acts basically as a mini-browser.
16
Simple GUI Example Java
  • import javax.swing.
  • import java.awt.
  • public class Test extends JApplet
  • public void init()
  • Container contentPane getContentPane()
  • Icon icon new ImageIcon("swing.gif",
  • "An animated GIF of Duke on a swing")
  • JLabel label new JLabel("Swing!", icon,
  • SwingConstants.CENTER)
  • contentPane.add(label, BorderLayout.CENTER)

JApplet has an instance of BorderLayout set for
its content pane. BorderLayout.CENTER is
default. Contrast AWTs Applet class uses
FlowLayout.
17
Simple GUI Example HTML
  • ltHTMLgt
  • ltHEADgt
  • lttitlegtTestlt/titlegt
  • lt/HEADgt
  • ltBODYgt
  • ltapplet code"Test.class
  • width300
  • height150gt
  • lt/appletgt
  • lt/BODYgt
  • lt/HTMLgt

18
Contrast with equivalent application
  • import javax.swing.
  • import java.awt.
  • import java.awt.event.
  • public class Test extends JFrame
  • public Test()
  • super("An Application")
  • Container contentPane getContentPane()
  • Icon icon new ImageIcon("swing.gif",
  • "An animated GIF of Duke on a swing")
  • JLabel label new JLabel("Swing!", icon,
  • SwingConstants.CENTER)
  • contentPane.add(label, BorderLayout.CENTER)

19
Contrast with equivalent application (cont)
  • public static void main(String args)
  • final JFrame f new Test()
  • f.setBounds(100,100,300,250)
  • f.setVisible(true)
  • f.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
  • f.addWindowListener(new WindowAdapter()
  • public void windowClosed(WindowEvent e)
  • System.exit(0)
  • )

20
Note s
  • Applet code is shorter
  • Need no main method for an applet
  • Browser does many things for us
  • Instantiates the class
  • Sets the applet size
  • Deals with closing events
  • Application main needs to
  • Create the instance
  • Set the size
  • Set the visibility
  • Handle closing events

21
Second GUI example
  • import javax.swing.JApplet
  • import java.awt.
  • import java.awt.event.
  • public class EventOnePointOne extends JApplet
    implements ActionListener
  • Button one
  • boolean toggle true
  • public void init()
  • one new Button(push me")
  • Container pane getContentPane()
  • pane.add(one)
  • one.addActionListener(one)
  • public void actionPerformed(ActionEvent e)
  • if (toggle)
  • setBackground(Color.white)
  • toggle false

22
JMenuBar
  • JApplets have the ability to have a menu bar
  • Similar to the menu bar of an application (frame)
  • Provided by JMenuBar class
  • Can attach a JMenu instance
  • Snippets of code Container cpgetContentPane()
    JMenuBar menubarnew JMenuBar() JMenu menunew
    JMenu(Options) menu.add(Red
    background) menu.add(Blue background) menu.
    add(Exit) menubar.add(menu) setJMenuBar(menu
    bar) cp.setLayout(new FlowLayout()) cp.add(new
    Jbutton(Click))

23
Package strangeness
  • Caution! Installation issue A Java package
    dictates a folder structure!
  • Trying to install a prewritten applet from
    somewhere?
  • Did you use a package statement in your applet
    code?
  • If yes to either of these, you need to understand
    that packages imply a folder (directory)
    structure!
  • Affects where you MUST place the applets
    bytecode file (WhatEverApplet.class) in relation
    to your HTML source file.
  • This then determines how you must link to the
    applet via your HTML code.

Beware package ? folder structure
24
Example with Package Statement
  • package examples.applet
  • import javax.swing.JApplet
  • import java.awt.
  • public class PackageApplet extends JApplet
  • // paint can be used to draw an applet
  • public void paint(Graphics g)
  • g.drawString("Hello World", 25, 50)
  • // paint
  • // PackageApplet

25
PackageApplet.HTML
  • ltHTMLgt
  • ltBODYgt
  • ltAPPLET CODE
  • examples\applet\PackageApplet.class
  • WIDTH300 HEIGHT300gt
  • lt/APPLETgt
  • lt/BODYgt
  • lt/HTMLgt

26
Trick 1 Power of Versatility -Applet Parameters
  • Passes information to the applet from the applet
    tag within the HTML file
  • Provides for very easy flexibility
  • Prevents unnecessary code editing and
    recompilation
  • Easy to use!

27
Power of VersatilityApplet Parameters
import java.awt. import javax.swing.JApplet pub
lic class AppletWithParams extends JApplet
String someText public String
getParameter(String key, String def) return
(getParameter(key) ! null ? getParameter(key)
def) public void init() someText
this.getParameter("someText",
"You can
change this text!") public void
paint(Graphics g) g.drawString(someText,
100, 200)
28
Using Applet Parameters - HTML
  • ltHTMLgtltHEADgtlt/HEADgt
  • ltBODYgt
  • ltAPPLET
  • CODE "AppletWithParams.class"
  • WIDTH 400
  • HEIGHT 300gt
  • ltPARAM NAME "someText"
  • VALUE "This text is
    from HTML file!"gt
  • lt/APPLETgt
  • lt/BODYgt
  • lt/HTMLgt

Notice that the parameters are given as NAME
VALUE pairs.If you have more parameters, youll
Simply have additional PARAM tags.
29
Trick 2 Application/Applet Hybrid
  • Is it an application? All applications need a
    main method
  • Is it an applet? There are other methods we
    need
  • init perhaps
  • paint or paintComponent methods perhaps
  • Can it be both an application and an
    applet?? YES!
  • Most IDEs can do this magic for you automatically
  • How can you do it? - Easy, the steps are pretty
    mechanical

30
Hybrid Java Code
  • import javax.swing.
  • import java.awt.
  • import java.awt.event.
  • public class Hybrid extends JApplet
  • public void init()
  • Container contentPane getContentPane()
  • Icon icon new ImageIcon("swing.gif")
  • JLabel label new JLabel(icon)
  • contentPane.setLayout(new FlowLayout())
  • contentPane.add(label new JLabel(icon))
  • contentPane.add(label)
  • // init method

31
Hybrid Java Code (cont.)
  • public static void main(String args)
  • final JFrame f new JFrame()
  • JApplet applet new Hybrid()
  • applet.init()
  • f.setContentPane(applet.getContentPane())
  • f.setBounds(100,100,308,199)
  • f.setTitle("An Application")
  • f.setVisible(true)
  • f.setDefaultCloseOperation(
  • WindowConstants.DISPOSE_ON_CLOSE)
  • f.addWindowListener(new WindowAdapter()
  • public void windowClosed(WindowEvent e)
  • System.exit(0)
  • )
  • // main method
  • // Hybrid class

32
Running a Hybrid
  • Compile using javac HybridApplet.java
  • Run using appletviewer and HybridApplet.html appl
    etviewer HybridApplet.htmlOR
  • Run using javac HybridApplet(Basically main
    then does everything a browser would do for us
    automatically.)

33
Trick 3 Converting an Existing Application to
an Applet (generic guide)
  • Make an HTML page with an applet tag to drive the
    applet
  • Remove the main method
  • Trivial to do if its only task was to create a
    frame object
  • The browser will create an applet object for us
  • More tricky if main is not so simple
  • Convert the JPanel class to a JApplet class
  • Make sure this class is public!
  • Remove these if present
  • setSize calls
  • addWindowListener calls
  • setTitle calls
  • Replace constructor with init method

34
Trick 4 Using ToolTips with applets
  • A ToolTip is a hint that pops up when the mouse
    hesitates over an area
  • Can be associated with a given component
  • Can be associated with regions image maps

35
Using ToolTip with Component
  • import javax.swing.
  • import java.awt.
  • import java.awt.event.
  • public class ToolTipTest extends JApplet
  • public void init()
  • Container contentPane getContentPane()
  • JButton button new JButton("I've got a
    tooltip")
  • button.setMnemonic(KeyEvent.VK_G)
  • button.setToolTipText(
  • blah blah blah tooltip")
  • contentPane.setLayout(new FlowLayout())
  • contentPane.add(button)

36
Using ToolTips with ImageMap
  • import javax.swing.
  • import java.awt.
  • import java.awt.event.
  • public class ToolTipsBasedOnMousePosition extends
    JApplet
  • public void init()
  • Container contentPane getContentPane()
  • ImageMap map new ImageMap("tiger.gif")
  • contentPane.setLayout(new FlowLayout())
  • contentPane.add(map)

37
Using ToolTips with ImageMap (cont)
  • class ImageMap extends JLabel
  • private Rectangle
  • teeth new Rectangle(62,203,80,55),
  • nose new Rectangle(37,164,130,30),
  • ear new Rectangle(228,10,65,55),
  • rEye new Rectangle(137,103,20,17),
  • lEye new Rectangle(65,97,16,15)
  • public ImageMap(String imageName)
  • super(new ImageIcon(imageName))
  • setToolTipText("tiger!")

38
Using ToolTips with ImageMap (cont)
  • public String getToolTipText(MouseEvent e)
  • Point p e.getPoint()
  • String s null
  • if(teeth.contains(p))
  • s "ooooh, big teeth!"
  • else if(nose.contains(p))
  • s "keen sense of smell"
  • else if(ear.contains(p))
  • s "acute hearing"
  • else if(rEye.contains(p) lEye.contains(p))
  • s "excellent vision"
  • return s null ? getToolTipText() s

39
Give us your thoughts! www.coursesurvey.gatech.ed
u
40
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com