CS 4273 Distributed System Technologies and Programming I
CS 4273: 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 = “Dir. Or. URL” CODE = “Local. class” NAME = “This. Applet. Name” WIDTH=pixels HEIGHT=pixels ALIGN = Alignment. Value //LEFT, RIGHT, TOP , …… VSPACE=pixels HSPACE=pixels ALT = “Alternative. Text. If. Applet. Not. Working” > <PARAM NAME = Parameter. Name VALUE = Parameter. Value>. . . </APPLET> 2
Passing Parameters to Applets • Applets get parameters from <PARAM> fields: <APPLET CODE="Java. Greeting. class" WIDTH=100 HEIGHT=50> <PARAM NAME=Greeting VALUE=”Hello, Good Morning”> </APPLET> • Code of getting the parameter value in the applet: String Greeting. Words = get. Parameter("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 Btn. Adapter implements Action. Listener { public class music extends JApplet { private int id; Audio. Clip music. Once, music. Loop; Btn. Adapter( int button. ID) { public void init() { id = button. ID; add (play. Btn = new Button("Play")); } play. Btn. add. Action. Listener(new Btn. Adapter (0)); add (loop. Btn = new Button("Loop")); public void action. Performed (Action. Event e) { add (stop. Btn = new Button("Stop")); switch (id) { stop. Btn. add. Action. Listener( new Btn. Adapter (2)); case 0: music. Once. play(); music. Once = get. Audio. Clip(get. Document. Base(), “TAM. au"); break; music. Loop = get. Audio. Clip(get. Document. Base(), "deng 0. au"); case 1: music. Loop. loop(); } break; case 2: music. Loop. stop(); public void start() { } music. Loop. loop(); } } } public void stop() { music. Loop. stop(); } 5
paint, repaint & paint. Component • 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 paint. Component(). For painting a sub-region of applet’s display area (i. e. , Jcomponent), you need to override paint. Component(), instead of paint() invokes paint. Component(). 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 Audio. Clip object and then play it. Get an audio clip by: – Audio. Clip get. Audio. Clip(URL url, String name) • Three methods on Audio. Clip 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 Audio. Clips class Btn. Adapter implements Action. Listener { public class audio. Player extends JApplet { private int id; Audio. Clip music. Once, music. Loop; Btn. Adapter( int button. ID) { public void init() { id = button. ID; add (play. Btn = new Button("Play")); } play. Btn. add. Action. Listener(new Btn. Adapter (0)); add (loop. Btn = new Button("Loop")); public void action. Performed (Action. Event e) { add (stop. Btn = new Button("Stop")); switch (id) { stop. Btn. add. Action. Listener( new Btn. Adapter (2)); case 0: music. Once. play(); music. Once = get. Audio. Clip(get. Document. Base(), “sun. au"); break; music. Loop = get. Audio. Clip(get. Document. Base(), "deng. au"); case 1: music. Loop. loop(); } break; case 2: music. Loop. stop(); public void start() { } music. Loop. loop(); } } } public void stop() { music. Loop. 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. create. Realized. Player(media. URL) • Get a video display panel and a control panel, and add them to applet: video. Panel = player. get. Visual. Component(); control. Panel = player. get. Control. Panel. Component(); add(“center”, video. Panel); add(“south”, control. Panel); • Control methods on the player object: player. start(); player. stop(); player. close() 10
Example of Playing Video in Applets public class video. Player extends JApplet { Player player; public void init() { URL media. URL = new URL(get. Document. Base(), "bailey. mpg"); player = Manager. create. Realized. Player(media. URL); Component video = player. get. Visual. Component(); Component controls = player. get. Control. Panel. Component(); 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 get. Image(URL url, String name) paint the image by: draw. Image(image, x, y, observer) An example: public class Image. Test extends Applet { { Image the. Image = null; public void init() { the. Image = get. Image(get. Document. Base(), "pg 9. gif"); } public void paint(Graphics g) { g. draw. Image(the. Image, 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 = get. Document. Base(); for (int i = 1; i <= 8; i++) { Image img = get. Image(base, "image/bunny" + i +". gif"); frames. add. Element(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. element. At(cur_frame-1); g. draw. Image(img, cur_frame*30, 0, this); } } 13
Steps of a Simple 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 Timer. Listener()); • The timer generates an action event in interval of delay and Timer. Listener() is an action. Listener class that handles this action event. Methods for Timer control: timer. set. Delay(delay); timer. start(); timer. stop(); 14
Example of Animation using Timer public void paint(Graphics g) { public class bounce. Ball extends JApplet { …………. . . . int delay = 100, x = 0, y = 20, radius = 10, dx = 10, dy = 10; x += dx; public Timer timer = new Timer(delay, new Timer. Listener()); y += dy; public void init() { g. set. Color(Color. red); panel. add(bt. Suspend = new JButton("Suspend")); g. fill. Oval(x-radius, y-radius, radius*2); bt. Suspend. add. Action. Listener(new Button. Adapter()); } panel. add(bt. Resume = new JButton("Resume")); class Timer. Listener implements Action. Listener { bt. Resume. add. Action. Listener(new Button. Adapter()); public void action. Performed(Action. Event e) { JScroll. Bar scroll. Bar = new JScroll. Bar(); repaint(); scroll. Bar. set. Orientation(JScroll. Bar. HORIZONTAL); } scroll. Bar. add. Adjustment. Listener(new Scroll. Adapter()); } class Button. Adapter implements Action. Listener { add(scroll. Bar, Border. Layout. NORTH); public void action. Performed (Action. Event e) { add(display. Area, Border. Layout. CENTER); if(e. get. Source() == bt. Suspend) add(panel, Border. Layout. SOUTH); timer. stop(); if(e. get. Source() == bt. Resume) timer. start(); } } public void start() { } timer. start(); class Scroll. Adapter implements Adjustment. Listener { } public void adjustment. Value. Changed(Adjustment. Event e) { public void stop() { timer. set. Delay(scroll. Bar. get. Maximum() - e. get. Value()); timer. stop(); } } } 15
Media Tracker • • Media. Tracker 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 Media. Tracker object by: Media. Tracker my. Tracker = new Media. Tracker(this); • Useful methods of Media. Tracker class: add. Image(img, id), add the img into the Tracker is. Error. Any(), if loading process has an error check. ID (id), check if the image is loaded check. All (), if all images are loaded wait. For. ID (id), wait. For. All (), block the current executing thread until all images are loaded. 16
Example of using Media. Tracker public class Image. Applet extends JApplet { Image my. Img = null; Media. Tracker my. Tracker = null; public void init() { my. Tracker = new Media. Tracker(this); my. Img = get. Image(get. Document. Base(), “me. gif”); my. Tracker. add. Image(my. Img, 0); } public void paint(Graphics g) { if (my. Tracker. is. Error. Any()) { g. draw. String(“errors in loading”, 10); return; } else if (my. Tracker. check. All(true)) { g. draw. Image(my. Img, 0, 0, this); } else { g. draw. String(“image loading…”, 10); repaint(100) // recursive call paint every 100 ms } } } 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 get. Document. Base() // URL of this web page URL get. Code. Base() // URL of this applet • Examples cat = get. Image (get. Document. Base(), “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 …… …… Applet 2. recv. Msg(m) browser (at the client side) without the …… recv. Msg(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 recver. Name = get. Parameter("RECEIVER") 2. Sender gets the receiver applet by recver = get. Applet. Context(). get. Applet(recver. Name) 3. Sender invokes the receiver’s method by reply_msg = ((receiver) recver). recv. Msg(msg) // “recv. Msg” 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 Action. Listener { public void init() { recv. Name = get. Parameter("RECEIVER"); //. . . set the GUI } public void action. Performed(Action. Event event) { String reply_msg, msg = “test of applet message passing"; Applet recver = null; //Get the receiver applet recver = get. Applet. Context(). get. Applet(recver. Name); // call receiver applet’s method. reply_msg = ((receiver)recver). recv. Msg(my. Name, msg); status. append(“Replied msg: " + reply_msg +"n"); msg = reply_msg; } } 22
The receiver program // receiver. java public class receiver extends JApplet implements Action. Listener { private JButton button = new JButton("Clear"); private JText. Area status = new JText. Area(5, 60); public void init() { button. add. Action. Listener(this); add("North", button); add("Center", status); add("South", new JLabel("My name is "+ get. Parameter("NAME"))); } public String recv. Msg(String sender. Name, String msg) { status. append("Received from " + sender. Name +": " + msg +"n"); i++; return msg+i; // echo received message back } public void action. Performed(Action. Event event) { status. set. Text(""); i = 0; } } 23
- Slides: 23