CS2 - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

CS2

Description:

Enable us to run java code embedded in a web page ... s = 'ooooh, big teeth!'; else if(nose.contains(p)) s = 'keen sense of smell' ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 42
Provided by: BillL161
Category:
Tags: cs2 | ooooh

less

Transcript and Presenter's Notes

Title: CS2


1
CS2
  • Introduction to
  • Object Oriented Programming
  • Applets

2
  • CS 1322 Official Final Exam Schedule
  • Section B (1200-145 lecture)
  • Lecturer Bill Leahy
  • Final Exam
  • Date August 1, 2001
  • Time 250-540
  • Location Physics L3 (Normal class meeting
    location)
  • Bring pencils, eraser. No books, notes,
    calculators, etc.
  • No one will be admitted after 305 p.m.

3
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!

4
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

5
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)

6
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

7
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

8
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 directly
    applicable to JApplets!

9
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.

10
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

11
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

12
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

13
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
14
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

15
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.
16
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.
17
Simple GUI Example Java
  • import javax.swing.
  • import java.awt.
  • public class Simple 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.
18
Simple GUI Example HTML
  • ltHTMLgt
  • ltHEADgt
  • lttitlegtSimplelt/titlegt
  • lt/HEADgt
  • ltBODYgt
  • ltapplet codeSimple.class
  • width300
  • height150gt
  • lt/appletgt
  • lt/BODYgt
  • lt/HTMLgt

19
Contrast with equivalent application
  • import javax.swing.
  • import java.awt.
  • import java.awt.event.
  • public class SimpleAp extends JFrame
  • public SimpleAp()
  • 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)
  • // SimpleAp( )

20
Contrast with equivalent application (cont)
  • public static void main(String args )
  • final JFrame f new SimpleAp()
  • 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)
  • )
  • // main( )
  • // SimpleAp

21
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

22
Second GUI example
  • import javax.swing.JApplet
  • import java.awt.
  • import java.awt.event.
  • public class GUI2 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(this)
  • one.setBackground(Color.yellow)
  • public void actionPerformed(ActionEvent e)
  • if (toggle)
  • one.setBackground(Color.white)
  • toggle false
  • else
  • one.setBackground(Color.yellow)

23
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))

24
Package strangeness
  • Caution! Installation issue A Java package
    dictates a folder structure!
  • Trying to install a prewritten applet from
    somewhere?
  • Or 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
25
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

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

27
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!

28
Power of VersatilityApplet Parameters
import java.awt. import javax.swing.JApplet pub
lic class AppletWithParams extends JApplet
String someText public String
myGetParameter(String key,
String def) return
(getParameter(key) ! null ?
getParameter(key) def) //
myGetParameter public void init()
someText myGetParameter("someText",
"You can change this text!") // init
public void paint(Graphics g)
g.drawString(someText, 100, 200) // paint
// AppletWithParams
29
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.
30
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

31
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

32
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

33
Running a Hybrid
  • Compile using javac Hybrid.java
  • Run using appletviewer and HybridApplet.html appl
    etviewer Hybrid.htmlOR
  • Run using java Hybrid(Basically main then does
    everything a browser would do for us
    automatically if it were running as a true
    applet.)

34
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

35
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

36
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)

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

38
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!")
  • // ImageMap

39
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
  • // getToolTipText
  • // ToolTipImageMap

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