1 / 23

CS4273: Distributed System Technologies and Programming I

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

aleta
Download Presentation

CS4273: Distributed System Technologies and Programming I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS4273: Distributed System Technologies and Programming I Lecture 3: Java Applets and Animations

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

  3. 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");

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

  5. 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(); } 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(); } } } Example of an Applet

  6. 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().

  7. Object Component Container Window JPanel Frame JApplet 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.

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

  9. 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(); } 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(); } } } Example of Playing AudioClips

  10. Play 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(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()

  11. 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(); } }

  12. 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); } }

  13. 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); } } Eample of Animation using Thread

  14. Steps 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.

  15. 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(JScrollBar.HORIZONTAL); scrollBar.addAdjustmentListener(new ScrollAdapter()); add(scrollBar, BorderLayout.NORTH); add(displayArea, BorderLayout.CENTER); add(panel, BorderLayout.SOUTH); timer.start(); } public void start() { timer.start(); } public void stop() { timer.stop(); } public void paint(Graphics g) { …………....... x += dx; y += dy; g.setColor(Color.red); g.fillOval(x-radius, y-radius, radius*2, radius*2); } class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { repaint(); } } class ButtonAdapter implements ActionListener { public void actionPerformed (ActionEvent e) { if(e.getSource() == btSuspend) timer.stop(); if(e.getSource() == btResume) timer.start(); } } class ScrollAdapter implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent e) { timer.setDelay(scrollBar.getMaximum() - e.getValue()); } } Example of Animation using Timer

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

  17. 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 } } }

  18. 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”);

  19. Applet 1 Applet 2 …… …… recvMsg(m) { …… } …… Applet2.recvMsg(m) …… 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). • The message passing is done inside the browser (at the client side) without the server involved.

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

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

  22. 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;} }

  23. 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; } }

More Related