Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Applets For a tutorial, see http://java.sun.com/docs/books/tutorial/applet/overview/index.html Applets Special Java programs (without a “main”) callable from HTML and executed in a graphic context. They can be executed by: a Java enabled Web Browser; ad-hoc programs (e.g. Sun AppletViewer). 1 1 Applets Every applet is implemented by creating a subclass of the Applet class. The hierarchy determines much of what an applet can do and how. Applet Lifecycle An applet can react to major events in the following ways: It can initialize itself. init() It can start running. start() It can draw some graphics. paint() It can respond to user-generated events (Mouse, keyboard, menus…). handleEvent() It can stop running. stop() It can perform a final cleanup, in preparation for being unloaded. destroy() 2 2 Applet Lifecycle init() Multithreading! start() handleEvent() stop() destroy() Whenever it’s needed, at lower priority paint() Actually, more threads are active behind the scenes. handleEvent() This code is part of the AWT (1.0 Event Model) public boolean handleEvent(Event evt) { switch (evt.id) { case Event.MOUSE_ENTER: return mouseEnter(evt, evt.x, evt.y); case Event.MOUSE_EXIT: return mouseExit(evt, evt.x, evt.y); case Event.MOUSE_MOVE: return mouseMove(evt, evt.x, evt.y); case Event.MOUSE_DOWN: return mouseDown(evt, evt.x, evt.y); case Event.MOUSE_DRAG: return mouseDrag(evt, evt.x, evt.y); case Event.MOUSE_UP: return mouseUp(evt, evt.x, evt.y); 3 3 handleEvent() case case case case Event.KEY_PRESS: Event.KEY_ACTION: return keyDown(evt, evt.key); Event.KEY_RELEASE: Event.KEY_ACTION_RELEASE: return keyUp(evt, evt.key); case Event.ACTION_EVENT: case Event.GOT_FOCUS: return action(evt, evt.arg); return gotFocus(evt, evt.arg); case Event.LOST_FOCUS: return lostFocus(evt, evt.arg); } return false; } Applets-Event handling To react to an event, an applet must override either the appropriate event-specific method or the handleEvent method. For example, adding the following code to the Simple applet makes it respond to mouse clicks. import java.awt.Event; ... public boolean mouseDown(Event event, int x, int y) { addItem("click!... "); return true; } 4 4 HTML 3.2: Java Applet Support <applet code=“Name.class”height=“150” width=“300”> <param name=“time” value=“100”> <param name=“color” value=“red”> This Browser does not support applets </Applet> ted a c re p e D in 4.0 L HT M Objects (HTML 4.0) The new tag OBJECT is defined. It passes to the browser Info needed to load non-native datatypes (applets, plugins, Active-X controls ecc.) The PARAM tag allows to pass parameters to the applet Or to the plugin. <OBJECT HEIGHT=… WIDTH=… CLASSID=…> <PARAM NAME=… VALUE=…> </OBJECT> 5 5 Applet example package demoApplet; import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { String var0; StringBuffer buffer; //Construct the applet public SimpleApplet() { } //Initialize the applet public void init() { buffer = new StringBuffer(); addItem("initializing... "); } Applet example //Start the applet public void start() { addItem("starting... "); addItem("Parameter is: "+getParameter("param0")); } //Stop the applet public void stop() { addItem("stopping... "); } //Destroy the applet public void destroy() { addItem("destroying... "); } void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } 6 6 Applet example public void paint(Graphics g) { int red = (int)(Math.random() * 255); int green = (int)(Math.random() * 255); int blue = (int)(Math.random() * 255); g.setColor(new Color(red, green, blue)); System.out.println(red+green+blue); //Draw a Rectangle around the applet's display area. g.fillRect(0, 0, size().width - 1, size().height - 1); g.setColor(new Color(0, 0, 0)); //Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } } HTML page (tag Applet) <head> <title> HTML Test Page </title> </head> <body> demoApplet.SimpleApplet will appear below in a Java enabled browser.<br> <applet codebase = "." code = "demoApplet.SimpleApplet.class" name = "TestApplet" width = "400" height = "300" hspace = "0" vspace = "0" align = "middle" > Your browser cannot show applets <param name = "param0" value = "hello"> </applet> </body> </html> 7 7 HTML page (tag Object) <head> <title> HTML Test Page </title> </head> <body> demoApplet.SimpleApplet will appear below in a Java enabled browser.<br> <object classid="java:demoApplet.SimpleApplet.class"> <param name = "param0" value = "hello" valuetype="data"> Your browser cannot show applets <param name = "param0" value = "hello"> </object> </body> </html> JApplet An extended version of java.applet.Applet that adds support for the JFC/Swing component architecture. You can find taskoriented documentation about using JApplet in The Java Tutorial, in the section How to Make Applets. The JApplet class is slightly incompatible with java.applet.Applet. JApplet contains a JRootPane as it's only child. The contentPane should be the parent of any children of the JApplet. This is different than java.applet.Applet, e.g. to add a child to an an java.applet.Applet you'd write: applet.add(child); However using JApplet you need to add the child to the JApplet's contentPane instead: applet.getContentPane().add(child); 8 8 Java-JavaScript interaction: JSObject JSObject allows Java to manipulate objects that are defined in JavaScript. Values passed from Java to JavaScript are converted as follows: JSObject is converted to the original JavaScript object. Any other Java object is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object. Converting this wrapper to a string will call the toString method on the original object, converting to a number will call the floatValue method if possible and fail otherwise. Converting to a boolean will try to call the booleanValue method in the same way. Java arrays are wrapped with a JavaScript object that understands array.length and array[index]. A Java boolean is converted to a JavaScript boolean. Java byte, char, short, int, long, float, and double are converted to JavaScript numbers. Note If you call a Java method from JavaScript, this conversion happens automatically--you can pass in "int" argument and it works. Java-JavaScript interaction: JSObject Values passed from JavaScript to Java are converted as follows: Objects that are wrappers around Java objects are unwrapped. Other objects are wrapped with a JSObject. Strings, numbers, and booleans are converted to String, Float, and Boolean objects respectively. Examples (String) window.getMember("name") (JSObject) window.getMember("document") 9 9 Java-JavaScript interaction: JSObject The netscape.javascript.JSObject class has the following methods: Method Description Call Calls a JavaScript method Eval Evaluates a JavaScript expression getMember Retrieves a named member of a JavaScript object getSlot Retrieves an indexed member of a JavaScript object removeMember Removes a named member of a JavaScript object setMember Sets a named member of a JavaScript object setSlot Sets an indexed member of a JavaScript object toString Converts a JSObject to a string The netscape.javascript.JSObject class has the following static methods: getWindow Gets a JSObject for the window containing the given applet Java-JavaScript interaction: applet side package javascript; import netscape.javascript.*; import java.applet.*; import java.awt.*; public class MyApplet extends Applet { private JSObject mainWindow; private JSObject pageDoc; private JSObject location; private String s; public String comment="instanceVarContent"; public void init() { System.out.println("initing"); mainWindow = JSObject.getWindow(this); pageDoc = (JSObject) mainWindow.getMember("document"); location = (JSObject) mainWindow.getMember("location"); s = (String) location.getMember("href"); // document.location.href } 10 10 Java-JavaScript interaction: applet side public int r=0; public int g=255; public int b=0; public void start(){ s=(String)mainWindow.call("f",null); String[] stringArgs = new String[1]; stringArgs[0] = "5"; s=(String)mainWindow.call("g", stringArgs); System.out.println (" Calling g returned "+s); } public void paint(Graphics gra) { if (s==null) s="NULL"; gra.setColor(new Color(r,g,b)); Dimension d=this.getSize(); gra.fillRect(0,0,d.width,d.height); gra.setColor(new Color(0,0,0)); gra.drawString("VERSION 1",80,80); gra.drawString(s,30,30); } Java-JavaScript interaction: applet side void changeColor(String s) { int x=Integer.parseInt(s); r=x; this.repaint(); } public String square(String sx) { int x=Integer.parseInt(sx); return new Integer(x*x).toString(); } } 11 11 Java-JavaScript interaction: JavaScript side <HTML> <head> <script> function g(x){return x+x} function f(){return "Called f()";} </script> </head> <body> <script type="text/JavaScript"> <!-- //hide script from old browsers document.write("<h2>JavaScript is enabled.</h2>") // end hiding contents from old browsers --> </script> <noscript><h2>JavaScript is not enabled, or your browser has restricted this file from showing active content.</h2></noscript> Java-JavaScript interaction: JavaScript side <script> <!-- //hide script from old browsers var jEnabled = navigator.javaEnabled(); if (jEnabled){ document.write("<h2>JAVA is enabled.</h2>") }else{ document.write("<h2>JAVA is <i>NOT</i> enabled.</h2>") } // end hiding contents from old browsers --> </script> <APPLET code="javascript.MyApplet.class" name="app" codebase="classes/" align="baseline" width="200" height="200" MAYSCRIPT> <PARAM NAME="param" VALUE="1"> If your browser is blocking the content, please click on the bar above. </APPLET> 12 12 Java-JavaScript interaction: JavaScript side <script language="Javascript"> document.write(f()); </script> <script language="Javascript"> document.write(app.comment); app.r=255; document.write(app.square("3"); </script> <form> <input name="ChangeColorButton" value="Change color" type="button" onclick="app.r=(app.r+100)%256;app.repaint()";/> </form> <form> <input title="writeButton" value="write on console" type="button" onclick='java.lang.System.out.println("a java message");';/> </form> </body> </html> 13 13