Title: CS4273: Distributed System Technologies and Programming I
1CS4273 Distributed System Technologies and
Programming I
- Lecture 3 Java Applets and Animations
2Java Applet
- Applet is a special kind of Java application
programs that are embedded into web pages. It
must run in a web-browser (or appletviewer). - It is downloaded from the network, and executed
locally. It is the idea of develop once and run
anywhere. - Applet tag in HTML
- ltAPPLET
- CODEBASE DirOrURL
- CODE Local.class
- NAME ThisAppletName
- WIDTHpixels HEIGHTpixels
- ALIGN AlignmentValue //LEFT, RIGHT, TOP,
- VSPACEpixels HSPACEpixels
- ALT AlternativeTextIfAppletNotWorking gt
- ltPARAM NAME ParameterName VALUE
ParameterValuegt - ...
- lt/APPLETgt
3Passing Parameters to Applets
- Applets get parameters from ltPARAMgt fields
- ltAPPLET CODE"JavaGreeting.class" WIDTH100
HEIGHT50gt - ltPARAM NAMEGreeting VALUEHello, Good
Morninggt - lt/APPLETgt
- Code of getting the parameter value in the
applet - String GreetingWords getParameter("Greeting")
4Applet Methods
- Applets do not have a main routine. Applet class
has many methods. You need to override some of
them to let applet perform your task. The Applet
methods are listed below in the order they are
called - init() called only once when the applet is
loaded. It initializes variables and initial
screen display. - start() called after init() and every time
returned to the page containing the applet after
gone off. It can be called repeatedly. - paint(Graphics g) it is also called by
repaint(). - stop() called when moving off the page. When
coming back, start() method is called. It is used
to stop time-consuming activities (animation
threads) when not seen. - destroy() called when the browser shuts down. It
deletes the applet and recalls all resources.
5Example of an Applet
- class BtnAdapter implements ActionListener
- private int id
- BtnAdapter( int buttonID)
- id buttonID
-
- public void actionPerformed (ActionEvent
e) - switch (id)
- case 0
musicOnce.play() - break
- case 1
musicLoop.loop() - break
- case 2
musicLoop.stop() -
-
-
- public class music extends JApplet
- AudioClip musicOnce, musicLoop
- public void init()
- add (playBtn new Button("Play"))
- playBtn.addActionListener(new BtnAdapter (0))
add (loopBtn new Button("Loop")) - add (stopBtn new Button("Stop"))
- stopBtn.addActionListener( new BtnAdapter (2))
- musicOnce getAudioClip(getDocumentBase(),
TAM.au") - musicLoop getAudioClip(getDocumentBase(),
"deng0.au") -
-
- public void start()
- musicLoop.loop()
-
- public void stop()
- musicLoop.stop()
-
6paint, repaint paintComponent
- Whenever you need to update the display, call
repaint() (you cannot call paint() directly).
repaint() invokes paint(). - In paint(), you usually start with super.paint(),
which performs some preparation work for you,
e.g., clear the display area. Without calling
super.paint(), the paint() will paint on top of
the existing drawings. - JComponent has method paintComponent(). For
painting a sub-region of applets display area
(i.e., Jcomponent), you need to override
paintComponent(), instead of paint(). paint()
invokes paintComponent().
7Applets and Applications
- JApplet is a subclass of JPanel.
- Create a component and add it to an applet in the
same way as adding it to a container, e.g.,
add(new button(start)), add(new Canvas()), etc.
8Play Audio Files in Applets
- When playing music, you need to get an AudioClip
object and then play it. Get an audio clip by - AudioClip getAudioClip(URL url, String name)
- Three methods on AudioClip objects
- play() it plays the audio file once and stop.
- loop() it plays the audio file repeatedly until
the stop method is called. - stop() it stops a loop play of an audio clip.
9Example of Playing AudioClips
- class BtnAdapter implements ActionListener
- private int id
- BtnAdapter( int buttonID)
- id buttonID
-
- public void actionPerformed (ActionEvent
e) - switch (id)
- case 0
musicOnce.play() - break
- case 1
musicLoop.loop() - break
- case 2
musicLoop.stop() -
-
-
- public class audioPlayer extends JApplet
- AudioClip musicOnce, musicLoop
- public void init()
- add (playBtn new Button("Play"))
- playBtn.addActionListener(new BtnAdapter (0))
add (loopBtn new Button("Loop")) - add (stopBtn new Button("Stop"))
- stopBtn.addActionListener( new BtnAdapter (2))
- musicOnce getAudioClip(getDocumentBase(),
sun.au") - musicLoop getAudioClip(getDocumentBase(),
"deng.au") -
-
- public void start()
- musicLoop.loop()
-
- public void stop()
- musicLoop.stop()
-
10Play Video in Applets
- Java Media Framework (JMF) API is used to play
and edit media files. You need to - download JMF package to IE to enable JMF
functions http//java.sun.com/javase/technologies/
desktop/media/jmf/2.1.1/download.html and, - compile programs with JMF library.
- The main JMF API includes
- A Manager class contains methods for playing and
manipulating media clips. - Create a player object out of URL of a video clip
by using Manager method - Player player Manager.createRealizedPlayer(me
diaURL) - Get a video display panel and a control panel,
and add them to applet - videoPanel player.getVisualComponent()
- controlPanel player.getControlPanelComponent()
- add(center, videoPanel)
- add(south, controlPanel)
- Control methods on the player object
- player.start()
- player.stop()
- player.close()
11Example of Playing Video in Applets
- public class videoPlayer extends JApplet
- Player player
- public void init()
- URL mediaURL new
URL(getDocumentBase(),"bailey.mpg") - player Manager.createRealizedPlay
er(mediaURL) - Component video
player.getVisualComponent() - Component controls
player.getControlPanelComponent() - add("Center", video)
- add("South", controls)
-
- public void start()
- if (player ! null)
player.start() -
- public void stop()
- if (player ! null)
player.stop() -
12Display Images
- get an Image by
- Image getImage(URL url, String name)
- paint the image by
- drawImage(image, x, y, observer)
- An example
- public class ImageTest extends Applet
-
- Image theImage null
- public void init()
- theImage getImage(getDocumentBas
e(), "pg9.gif") -
- public void paint(Graphics g)
- g.drawImage(theImage, 0, 0,
this) -
13Eample of Animation using Thread
- public class animation extends JApplet implements
Runnable - Thread runner
- Vector frames new Vector()
- int cur_frame, frame_delay 400
- public void init()
- URL base getDocumentBase()
- for (int i 1 i lt 8 i)
- Image img
getImage(base, - "image/bunny" i ".gif")
- frames.addElement(img)
-
- public void start()
- if (runner null)
- runner new
Thread(this) - runner.start()
-
- public void stop()
- runner null
-
- public void run()
- cur_frame 1
- while(runner ! null)
- Thread.sleep(frame_delay)
- repaint()
- if(cur_frame gt
frames.size()) - cur_frame 1
- else
- cur_frame
-
- public void paint(Graphics g)
- super.paint(g)
- Image img
- (Image)frames.elementAt(cur_frame-1)
- g.drawImage(img, cur_frame30, 0,
this) -
-
14Steps of a Simple Animation
- Animation using Timer class
- Create a Timer object
- new Timer(delay, new TimerListener())
- The timer generates an action event in interval
of delay and TimerListener() is an actionListener
class that handles this action event. - Methods for Timer control
- timer.setDelay(delay)
- timer.start()
- timer.stop()
- Animation using Thread
- In init(), load the images into frames (data
structure of a vector). - In start(), start a thread to do the animation.
- In run() of the thread, paint the cur-frame,
pause a while, and move forward the pointer of
frames. - In paint(), paint the image of the cur-frame.
15Example of Animation using Timer
- public void paint(Graphics g)
- .......
- x dx
- y dy
- g.setColor(Color.red)
- g.fillOval(x-radius, y-radius,
radius2, radius2) -
- class TimerListener implements ActionListener
- public void actionPerformed(Action
Event e) - repaint()
-
-
- class ButtonAdapter implements ActionListener
- public void actionPerformed
(ActionEvent e) - if(e.getSource()
btSuspend) - timer.stop()
- if(e.getSource()
btResume) - timer.start()
-
- public class bounceBall extends JApplet
- int delay 100, x 0, y 20, radius
10, dx 10, dy 10 - public Timer timer new Timer(delay, new
TimerListener()) - public void init()
- panel.add(btSuspend new
JButton("Suspend")) - btSuspend.addActionListener(new
ButtonAdapter()) - panel.add(btResume new
JButton("Resume")) - btResume.addActionListener(new
ButtonAdapter()) - JScrollBar scrollBar new
JScrollBar() - scrollBar.setOrientation(JScrollBa
r.HORIZONTAL) - scrollBar.addAdjustmentListener(ne
w ScrollAdapter()) - add(scrollBar, BorderLayout.NORTH)
- add(displayArea,
BorderLayout.CENTER) - add(panel, BorderLayout.SOUTH)
- timer.start()
-
- public void start()
16Media Tracker
- MediaTracker class provides methods to check
whether the loading of an image (a group of
images) is complete or not, and get status of
image loading. It is particularly useful in
managing a group of images. - Construct a MediaTracker object by
- MediaTracker myTracker new MediaTracker(this)
- Useful methods of MediaTracker class
- addImage(img, id), add the img into the Tracker
- isErrorAny(), if loading process has an error
- checkID (id), check if the image is loaded
- checkAll (), if all images are loaded
- waitForID (id),
- waitForAll (), block the current executing thread
until all images are loaded.
17Example of using MediaTracker
- public class ImageApplet extends JApplet
- Image myImg null
- MediaTracker myTracker null
- public void init()
- myTracker new MediaTracker(this)
- myImg getImage(getDocumentBase(), me.gif)
- myTracker.addImage(myImg, 0)
-
- public void paint(Graphics g)
- if (myTracker.isErrorAny())
- g.drawString(errors in loading, 10, 10)
- return
- else if (myTracker.checkAll(true))
- g.drawImage(myImg, 0, 0, this)
- else
- g.drawString(image loading, 10, 10)
- repaint(100) // recursive call paint every
100ms -
-
18Applet Network Access
- Security of an applet
- applets cannot run any local executable program.
- applets cannot read or write to the local
computers file system. - applets cannot communicate with any host other
than the server from which they are downloaded. - Getting data from originating server
- applets get data from their originating servers
- URL getDocumentBase() // URL of this web page
- URL getCodeBase() // URL of this of this applet
- Examples
- cat getImage (getDocumentBase(),
images/cat.gif)
19Message Passing between Applets
- When a web page contains several applets, it is
often required that the applets communicate with
each other. An applet can send messages to
another applet on the same page (communicating
applets must originate from the same server). - An applet sends a message to another via invoking
a method of the other applet. It is inter-applet
method invocation. - Applets identify each other by using their
- names (assigned in the HTML file).
- The message passing is done inside the
- browser (at the client side) without the
- server involved.
20HTML File Containing two Applets with Names
- lthtmlgt
- ltbodygt
- ltAPPLET CODE"sender.class" WIDTH450 HEIGHT300
NAMEBob"gt - ltPARAM NAMERECEIVER VALUEAlice"gt
- lt/APPLETgt
- ltAPPLET CODE"receiver.class" WIDTH450
HEIGHT300 NAMEAlice"gt - lt/APPLETgt
- lt/bodygt
- lt/htmlgt
21Steps for sending a message to another applet
- 1. Sender gets receivers name by
- recverName getParameter("RECEIVER")
- 2. Sender gets the receiver applet by
- recver getAppletContext().getApplet(recve
rName) - 3. Sender invokes the receivers method by
- reply_msg ((receiver) recver).recvMsg(msg)
- // recvMsg is a method of the receiver
(for receiving messages). - 4. The receivers method can return a value (or
string) that the sender can get as the reply of
its message.
22The sender program
- // sender.java
- public class sender extends Applet implements
ActionListener - public void init()
- recvName getParameter("RECEIVER")
- //... set the GUI
-
- public void actionPerformed(ActionEvent event)
- String reply_msg, msg test of applet message
passing" - Applet recver null
- //Get the receiver applet
- recver getAppletContext().getApplet(recverName)
-
- // call receiver applets method.
- reply_msg ((receiver)recver).recvMsg(myName,
msg) - status.append(Replied msg " reply_msg
"\n") - msg reply_msg
23The receiver program
- // receiver.java
- public class receiver extends JApplet implements
ActionListener - private JButton button new
JButton("Clear") - private JTextArea status new
JTextArea(5, 60) - public void init()
- button.addActionListener(this)
add("North", button) - add("Center", status)
- add("South", new JLabel("My name
is " getParameter("NAME"))) -
- public String recvMsg(String senderName, String
msg) - status.append("Received from "
senderName " " msg "\n") - i
- return msgi // echo received
message back - public void actionPerformed(ActionEvent event)
- status.setText("")
- i 0
-