CS4273: Distributed System Technologies and Programming I Lecture 3: Java Applets and Animations Java 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: <APPLET CODEBASE = “DirOrURL” CODE = “Local.class” NAME = “ThisAppletName” WIDTH=pixels HEIGHT=pixels ALIGN = AlignmentValue //LEFT, RIGHT, TOP, …… VSPACE=pixels HSPACE=pixels ALT = “AlternativeTextIfAppletNotWorking” > <PARAM NAME = ParameterName VALUE = ParameterValue> ... </APPLET> 2 Passing Parameters to Applets • Applets get parameters from <PARAM> fields: <APPLET CODE="JavaGreeting.class" WIDTH=100 HEIGHT=50> <PARAM NAME=Greeting VALUE=”Hello, Good Morning”> </APPLET> • Code of getting the parameter value in the applet: String GreetingWords = getParameter("Greeting"); 3 Applet 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. 4 Example of an Applet class BtnAdapter implements ActionListener { public class music extends JApplet { private int id; AudioClip musicOnce, musicLoop; BtnAdapter( int buttonID) { public void init() { id = buttonID; add (playBtn = new Button("Play")); } playBtn.addActionListener(new BtnAdapter (0)); add (loopBtn = new Button("Loop")); public void actionPerformed (ActionEvent e) { add (stopBtn = new Button("Stop")); switch (id) { stopBtn.addActionListener( new BtnAdapter (2)); case 0: musicOnce.play(); musicOnce = getAudioClip(getDocumentBase(), “TAM.au"); break; musicLoop = getAudioClip(getDocumentBase(), "deng0.au"); case 1: musicLoop.loop(); } break; case 2: musicLoop.stop(); public void start() { } musicLoop.loop(); } } } public void stop() { musicLoop.stop(); } 5 paint, 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 applet’s display area (i.e., Jcomponent), you need to override paintComponent(), instead of paint(). paint() invokes paintComponent(). 6 Applets 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. Object Component Container Window JPanel Frame JApplet 7 Play 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. 8 Example of Playing AudioClips class BtnAdapter implements ActionListener { public class audioPlayer extends JApplet { private int id; AudioClip musicOnce, musicLoop; BtnAdapter( int buttonID) { public void init() { id = buttonID; add (playBtn = new Button("Play")); } playBtn.addActionListener(new BtnAdapter (0)); add (loopBtn = new Button("Loop")); public void actionPerformed (ActionEvent e) { add (stopBtn = new Button("Stop")); switch (id) { stopBtn.addActionListener( new BtnAdapter (2)); case 0: musicOnce.play(); musicOnce = getAudioClip(getDocumentBase(), “sun.au"); break; musicLoop = getAudioClip(getDocumentBase(), "deng.au"); case 1: musicLoop.loop(); } break; case 2: musicLoop.stop(); public void start() { } musicLoop.loop(); } } } public void stop() { musicLoop.stop(); } 9 Play Video in Applets Java Media Framework (JMF) API is used to play and edit media files. You need to: 1) download JMF package to IE to enable JMF functions http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/download.html and, 2) 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(mediaURL) • 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() 10 Example of Playing Video in Applets public class videoPlayer extends JApplet { Player player; public void init() { URL mediaURL = new URL(getDocumentBase(),"bailey.mpg"); player = Manager.createRealizedPlayer(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(); } } 11 Display 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(getDocumentBase(), "pg9.gif"); } public void paint(Graphics g) { g.drawImage(theImage, 0, 0, this); } } 12 Eample 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 <= 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 >= 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_frame*30, 0, this); } } 13 Steps of a Simple Animation 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. 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(); 14 Example of Animation using Timer public void paint(Graphics g) { public class bounceBall extends JApplet { …………....... int delay = 100, x = 0, y = 20, radius = 10, dx = 10, dy = 10; x += dx; public Timer timer = new Timer(delay, new TimerListener()); y += dy; public void init() { g.setColor(Color.red); panel.add(btSuspend = new JButton("Suspend")); g.fillOval(x-radius, y-radius, radius*2, radius*2); btSuspend.addActionListener(new ButtonAdapter()); } panel.add(btResume = new JButton("Resume")); class TimerListener implements ActionListener { btResume.addActionListener(new ButtonAdapter()); public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = new JScrollBar(); repaint(); scrollBar.setOrientation(JScrollBar.HORIZONTAL); } scrollBar.addAdjustmentListener(new ScrollAdapter()); } class ButtonAdapter implements ActionListener { add(scrollBar, BorderLayout.NORTH); public void actionPerformed (ActionEvent e) { add(displayArea, BorderLayout.CENTER); if(e.getSource() == btSuspend) add(panel, BorderLayout.SOUTH); timer.stop(); if(e.getSource() == btResume) timer.start(); timer.start(); } } public void start() { } timer.start(); class ScrollAdapter implements AdjustmentListener { } public void adjustmentValueChanged(AdjustmentEvent e) { public void stop() { timer.setDelay(scrollBar.getMaximum() - e.getValue()); timer.stop(); } } } 15 Media 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. 16 Example 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 } } } 17 Applet Network Access Security of an applet: • applets cannot run any local executable program. • applets cannot read or write to the local computer’s 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”); 18 Message 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). Applet 2 • The message passing is done inside the ……Applet 1 …… …… Applet2.recvMsg(m) browser (at the client side) without the …… recvMsg(m) { …… server involved. } 19 HTML File Containing two Applets with Names <html> <body> <APPLET CODE="sender.class" WIDTH=450 HEIGHT=300 NAME=“Bob"> <PARAM NAME=RECEIVER VALUE=“Alice"> </APPLET> <APPLET CODE="receiver.class" WIDTH=450 HEIGHT=300 NAME=“Alice"> </APPLET> </body> </html> 20 Steps for sending a message to another applet 1. Sender gets receiver’s name by recverName = getParameter("RECEIVER") 2. Sender gets the receiver applet by recver = getAppletContext().getApplet(recverName) 3. Sender invokes the receiver’s method by reply_msg = ((receiver) recver).recvMsg(msg) // “recvMsg” is a method of the receiver (for receiving messages). 4. The receiver’s method can return a value (or string) that the sender can get as the reply of its message. 21 The 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 applet’s method. reply_msg = ((receiver)recver).recvMsg(myName, msg); status.append(“Replied msg: " + reply_msg +"\n"); msg = reply_msg;} } 22 The 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 msg+i; // echo received message back } public void actionPerformed(ActionEvent event) { status.setText(""); i = 0; } } 23