Download presentation
Presentation is loading. Please wait.
Published bySawyer Huller Modified over 10 years ago
1
Java Applets & Graphics INE2720 Web Application Software Development Essential Materials
2
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.2 Outline Applet restrictions Applet restrictions Basic applet and HTML template Basic applet and HTML template The applet life-cycle The applet life-cycle Customizing applets through HTML parameters Customizing applets through HTML parameters Methods available for graphical operations Methods available for graphical operations Loading and drawing images Loading and drawing images Controlling image loading Controlling image loading Java Plug-In and HTML converter Java Plug-In and HTML converter Control Java from JavaScript Control Java from JavaScript
3
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.3 Reviews: Java Language Object-Oriented Programming Object-Oriented Programming –Objects, Class, Inheritance, Interface Language Basics Language Basics –Variables, Operators, Expressions –Flow control, Loops Object Basics Object Basics –Create, use, cleanup objects Interfaces and Packages Interfaces and Packages
4
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.4 Applet Restrictions Do not read from the local (client) disk Do not read from the local (client) disk Do not write to the local (client) disk Do not write to the local (client) disk Do not open network connections other than to the server from which the applet was loaded Do not open network connections other than to the server from which the applet was loaded Do not link to client-side C code or call programs installed on the browser machine Do not link to client-side C code or call programs installed on the browser machine Cannot discover private information about the user Cannot discover private information about the user
5
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.5 Applet Template import java.applet.Applet; import java.awt.*; public class AppletTemplate extends Applet { // Variable declarations. // Variable declarations. public void init() { public void init() { // Variable initializations, image loading, etc. // Variable initializations, image loading, etc. } public void paint(Graphics g) { public void paint(Graphics g) { // Drawing operations. // Drawing operations. }} Browsers cache applets: in Netscape, use Shift-RELOAD to force loading of new applet. In IE, use Control-RELOAD Browsers cache applets: in Netscape, use Shift-RELOAD to force loading of new applet. In IE, use Control-RELOAD Can use appletviewer for initial testing Can use appletviewer for initial testing
6
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.6 Applet HTML Template <html><head> A Template for Loading Applets A Template for Loading Applets </head><body> <p> Error! You must use a Java-enabled browser. Error! You must use a Java-enabled browser. </applet></body></html>
7
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.7 Applet Example import java.applet.Applet; import java.awt.*; /** An applet that draws an image. */ public class JavaJump extends Applet { private Image jumpingJava; // Instance var declarations here private Image jumpingJava; // Instance var declarations here public void init() { // Initializations here public void init() { // Initializations here setBackground(Color.white); setBackground(Color.white); setFont(new Font("SansSerif", Font.BOLD, 18)); setFont(new Font("SansSerif", Font.BOLD, 18)); jumpingJava = getImage(getDocumentBase(), jumpingJava = getImage(getDocumentBase(), "images/Jumping-Java.gif"); "images/Jumping-Java.gif"); add(new Label("Great Jumping Java!")); add(new Label("Great Jumping Java!")); System.out.println("Yow! I'm jiving with Java."); System.out.println("Yow! I'm jiving with Java."); } public void paint(Graphics g) { // Drawing here public void paint(Graphics g) { // Drawing here g.drawImage(jumpingJava, 0, 50, this); g.drawImage(jumpingJava, 0, 50, this); }}
8
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.8 Applet Example, Result <HTML><HEAD> Jumping Java Jumping Java </HEAD> Jumping Java Jumping Java <P> <APPLET CODE="JavaJump.class" WIDTH=250 WIDTH=250 HEIGHT=335> HEIGHT=335> Sorry, this example requires Sorry, this example requires Java. Java. </APPLET></BODY></HTML>
9
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.9 Java Console Standard output, System.out.print, is sent to the Java Console Standard output, System.out.print, is sent to the Java Console –Navigator: open from Window menu –Communicator: open from Communicator … Tools menu –IE: open from View menu (enable from Tools … Internet Options … Advanced screen)
10
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.10 Applet Inheritance Hierarchy Applet class derives from the Abstract Window Toolkit (AWT) hierarchy. Applet class derives from the Abstract Window Toolkit (AWT) hierarchy.
11
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.11 Applet Life Cycle 1. public void init() - Called when applet is first initialized 2. public void start() –Called immediately after init and again revisited after browser left page containing applet –Used to start animation threads 3. public void paint(Graphics g) –Called by the browser after init and start, and again whenever the browser redraws the screen, (typically when part of the screen has been obscured and then reexposed) –This method is where user-level drawing is placed –Inherited from java.awt.Container 4. public void stop() –Called when the browser leaves the page –Used to stop animation threads 5. public void destroy() –Called when applet is killed (rarely used)
12
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.12 AWT Pre-Made UI Components AWT supplies the following UI components: AWT supplies the following UI components: –Buttons (java.awt.Button) –Checkboxes (java.awt.Checkbox) –Single-line text fields (java.awt.TextField) –Menus (java.awt.MenuItem) –Containers (java.awt.Panel) –Lists (java.awt.List)
13
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.13 Useful Applet Methods getCodeBase, getDocumentBase getCodeBase, getDocumentBase –The URL of the: Applet file - getCodeBase HTML file - getDocumentBase getParameter getParameter –Retrieves the value from the associated HTML PARAM element getSize getSize –Returns the Dimension (width, height) of the applet getGraphics getGraphics –Retrieves the current Graphics object for the applet –The Graphics object does not persist across paint invocations
14
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.14 Useful Applet Methods, (Continued) showDocument (AppletContext method) showDocument (AppletContext method) getAppletContext().showDocument(...) getAppletContext().showDocument(...) –Asks the browser to retrieve and a display a Web page –Can direct page to a named FRAME cell showStatus showStatus –Displays a string in the status line at the bottom of the browser getCursor, setCursor getCursor, setCursor –Defines the Cursor for the mouse, for example, CROSSHAIR_CURSOR, HAND_CURSOR, WAIT_CURSOR
15
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.15 Useful Applet Methods, (Continued) getAudioClip getAudioClip play play –Retrieves an audio file from a remote location and plays it –JDK 1.1 supports.au only. Java 2 also supports MIDI,.aiff and.wav getBackground, setBackground getBackground, setBackground –Gets/sets the background color of the applet –SystemColor class provides access to desktop colors getForeground, setForeground getForeground, setForeground –Gets/sets foreground color of applet (default color of drawing operations)
16
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.16 HTML APPLET Element...</applet> Required Attributes Required Attributes –CODE Designates the filename of the Java class file to load Designates the filename of the Java class file to load Filename interpreted with respect to directory of current HTML page (default) unless CODEBASE is supplied Filename interpreted with respect to directory of current HTML page (default) unless CODEBASE is supplied –WIDTH and HEIGHT Specifies area the applet will occupy Specifies area the applet will occupy Values can be given in pixels or as a percentage of the browser window width Values can be given in pixels or as a percentage of the browser window width
17
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.17 HTML APPLET Element, continued Other Attributes Other Attributes –ALIGN, HSPACE, and VSPACE Controls position and border spacing just like IMG element (in pixels) Controls position and border spacing just like IMG element (in pixels) –ARCHIVE Designates JAR file (zip file with.jar extension) containing all classes and images used by applet Designates JAR file (zip file with.jar extension) containing all classes and images used by applet Save considerable time download multiple class files Save considerable time download multiple class files –NAME Names the applet for interapplet and JavaScript communication Names the applet for interapplet and JavaScript communication –MAYSCRIPT (nonstandard) Permits JavaScript to control the applet Permits JavaScript to control the applet
18
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.18 Setting Applet Parameters Customizable HelloWWW Applet Customizable HelloWWW Applet Error! You must use a Java-enabled browser. Error! You must use a Java-enabled browser. </applet> Error! You must use a Java-enabled browser. Error! You must use a Java-enabled browser. </applet> Error! You must use a Java-enabled browser. Error! You must use a Java-enabled browser. </applet>
19
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.19 Reading Applet Parameters Use getParameter(name) to retrieve the value of the PARAM element and the name argument is case sensitive Use getParameter(name) to retrieve the value of the PARAM element and the name argument is case sensitive public void init() { public void init() { Color background = Color.gray; Color background = Color.gray; Color foreground = Color.darkGray; Color foreground = Color.darkGray; String backgroundType = getParameter("BACKGROUND"); String backgroundType = getParameter("BACKGROUND"); if (backgroundType != null) { if (backgroundType != null) { if (backgroundType.equalsIgnoreCase("LIGHT")) { if (backgroundType.equalsIgnoreCase("LIGHT")) { background = Color.white; background = Color.white; foreground = Color.black; foreground = Color.black; } else if (backgroundType.equalsIgnoreCase("DARK")) { } else if (backgroundType.equalsIgnoreCase("DARK")) { background = Color.black; background = Color.black; foreground = Color.white; foreground = Color.white; } }... }... }}
20
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.20 Reading Applet Parameters: Result
21
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.21 Useful Graphics Methods drawString(string, left, bottom) drawString(string, left, bottom) –Draws a string in the current font and color with the bottom left corner of the string at the specified location –One of the few methods where the y coordinate refers to the bottom of shape, not the top. But y values are still with respect to the top left corner of the applet window drawRect(left, top, width, height) drawRect(left, top, width, height) –Draws the outline of a rectangle (1-pixel border) in the current color fillRect(left, top, width, height) fillRect(left, top, width, height) –Draws a solid rectangle in the current color drawLine(x1, y1, x2, y2) drawLine(x1, y1, x2, y2) –Draws a 1-pixel-thick line from (x1, y1) to (x2, y2)
22
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.22 Useful Graphics Methods, continued drawOval, fillOval drawOval, fillOval –Draws an outlined and solid oval, where the arguments describe a rectangle that bounds the oval drawPolygon, fillPolygon drawPolygon, fillPolygon –Draws an outlined and solid polygon whose points are defined by arrays or a Polygon (a class that stores a series of points) –By default, polygon is closed; to make an open polygon use the drawPolyline method drawImage drawImage –Draws an image –Images can be in JPEG or GIF (including GIF89A) format
23
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.23 Graphics Color setColor, getColor setColor, getColor –Specifies the foreground color prior to drawing operation –By default, the graphics object receives the foreground color of the window –AWT has 16 predefined colors ( Color.red, Color.blue, etc.) or create your own color, new Color(r, g, b) –Changing the color of the Graphics object affects only the drawing that explicitly uses that Graphics object To make permanent changes, call the applet ’ s setForeground method. To make permanent changes, call the applet ’ s setForeground method.
24
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.24 Graphics Font setFont, getFont setFont, getFont –Specifies the font to be used for drawing text –Determine the size of a character through FontMetrics (in Java 2 use LineMetrics ) –Setting the font for the Graphics object does not persist to subsequent invocations of paint –Set the font of the window (I.e., call the applet ’ s setFont method) for permanent changes to the Graphics object –In JDK 1.1, only 5 fonts are available: Serif (aka TimesRoman ), SansSerif (aka Helvetica ), Monospaced (aka Courier ), Dialog, and DialogInput
25
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.25 Graphics Behavior Browser calls repaint method to request redrawing of applet Browser calls repaint method to request redrawing of applet –Called when applet first drawn or applet is hidden by another window and then re-exposed repaint() update(Graphics g) paint(Graphics g) “sets flag” Clears screen, Calls paint
26
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.26 Drawing Images Register the Image (from init ) Register the Image (from init ) Image image = getImage(getCodeBase(), "file"); Image image = getImage(getCodeBase(), "file"); Image image = getImage (url); Image image = getImage (url); –Loading is done in a separate thread –If URL is absolute, then try / catch block is required Draw the image (from paint ) Draw the image (from paint ) g.drawImage(image, x, y, window); g.drawImage(image, x, y, window); g.drawImage(image, x, y, w, h, window); g.drawImage(image, x, y, w, h, window); –May draw partial image or nothing at all –Use the applet ( this ) for the window argument
27
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.27 Loading Applet Image from Relative URL import java.applet.Applet; import java.awt.*; /** An applet that loads an image from a relative URL. */ public class JavaMan1 extends Applet { private Image javaMan; private Image javaMan; public void init() { public void init() { javaMan = getImage(getCodeBase(), javaMan = getImage(getCodeBase(),"images/Java-Man.gif"); } public void paint(Graphics g) { public void paint(Graphics g) { g.drawImage(javaMan, 0, 0, this); g.drawImage(javaMan, 0, 0, this); }}
28
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.28 Loading Applet Image from Absolute URL import java.applet.Applet; import java.awt.*; import java.net.*;... private Image javaMan; private Image javaMan; public void init() { public void init() { try { try { URL imageFile = URL imageFile = new URL("http://www.corewebprogramming.com" + new URL("http://www.corewebprogramming.com" + "/images/Java-Man.gif"); "/images/Java-Man.gif"); javaMan = getImage(imageFile); javaMan = getImage(imageFile); } catch(MalformedURLException mue) { } catch(MalformedURLException mue) { showStatus("Bogus image URL."); showStatus("Bogus image URL."); System.out.println("Bogus URL"); System.out.println("Bogus URL"); } }
29
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.29 Loading Images in Applications import java.awt.*; import javax.swing.*; class JavaMan3 extends JPanel { private Image javaMan; private Image javaMan; public JavaMan3() { public JavaMan3() { String imageFile = System.getProperty("user.dir") + String imageFile = System.getProperty("user.dir") + "/images/Java-Man.gif"; "/images/Java-Man.gif"; javaMan = getToolkit().getImage(imageFile); javaMan = getToolkit().getImage(imageFile); setBackground(Color.white); setBackground(Color.white); } public void paintComponent(Graphics g) { public void paintComponent(Graphics g) { super.paintComponent(g); super.paintComponent(g); g.drawImage(javaMan, 0, 0, this); g.drawImage(javaMan, 0, 0, this); }......
30
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.30 Loading Images in Applications (Continued)...... public void paintComponent(Graphics g) { public void paintComponent(Graphics g) { super.paintComponent(g); super.paintComponent(g); g.drawImage(javaMan, 0, 0, this); g.drawImage(javaMan, 0, 0, this); } public static void main(String[] args) { public static void main(String[] args) { JPanel panel = new JavaMan3(); JPanel panel = new JavaMan3(); WindowUtilities.setNativeLookAndFeel(); WindowUtilities.setNativeLookAndFeel(); WindowUtilities.openInJFrame(panel, 380, 390); WindowUtilities.openInJFrame(panel, 380, 390); }} See Swing chapter for WindowUtilities See Swing chapter for WindowUtilities
31
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.31 Java Plug-In Internet Explorer and Netscape (except Version 6) only support JDK 1.1 Internet Explorer and Netscape (except Version 6) only support JDK 1.1 Plug-In provides support for the latest JDK Plug-In provides support for the latest JDK –http://java.sun.com/products/plugin/ –Java 2 Plug-In > 5 Mbytes Requires modification of APPLET element to support OBJECT element (IE) or EMBED element (Netscape) Requires modification of APPLET element to support OBJECT element (IE) or EMBED element (Netscape) –Use HTML Converter to perform the modification
32
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.32 Java Plug-In HTML Converter
33
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.33 Java Plug-In HTML Converter “ Navigator for Windows Only ” conversion “ Navigator for Windows Only ” conversion <EMBED type="application/x-java-applet;version=1.3" CODE = "HelloWWW.class" CODEBASE = "applets" CODE = "HelloWWW.class" CODEBASE = "applets" WIDTH = 400 HEIGHT = 40 WIDTH = 400 HEIGHT = 40 BACKGROUND = "LIGHT" BACKGROUND = "LIGHT" scriptable=false scriptable=false pluginspage="http://java.sun.com/products/plugin/1.3/ pluginspage="http://java.sun.com/products/plugin/1.3/ plugin-install.html" plugin-install.html"> Error! You must use a Java-enabled browser. Error! You must use a Java-enabled browser.
34
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.34 Java Plug-In HTML Converter “ Internet Explorer for Windows and Solaris ” conversion “ Internet Explorer for Windows and Solaris ” conversion <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH = 400 HEIGHT = 40 WIDTH = 400 HEIGHT = 40 codebase="http://java.sun.com/products/plugin/1.3/ codebase="http://java.sun.com/products/plugin/1.3/ jinstall-13-win32.cab#Version=1,3,0,0"> jinstall-13-win32.cab#Version=1,3,0,0"> <PARAM NAME="type" <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3"> VALUE="application/x-java-applet;version=1.3"> Error! You must use a Java-enabled browser. Error! You must use a Java-enabled browser.
35
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.35 Application: Accessing Java from JavaScript Calling Java Methods Directly Calling Java Methods Directly –JavaScript can access Java variables and methods simply by using the fully qualified name. For instance: java.lang.System.out.println("Hello Console"); java.lang.System.out.println("Hello Console"); –Limitations: Can ’ t perform operations forbidden to applets Can ’ t perform operations forbidden to applets No try/catch, so can ’ t call methods that throw exceptions No try/catch, so can ’ t call methods that throw exceptions Cannot write methods or create subclasses Cannot write methods or create subclasses
36
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.36 Controlling Applets from JavaScript, Example MoldSimulation.html, cont. MoldSimulation.html, cont. Mold Propagation Simulation Mold Propagation Simulation <P> </APPLET><P> </APPLET><FORM> </FORM></BODY></HTML>
37
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.37 Controlling Applets from JavaScript, Example MoldSimulation.html MoldSimulation.html<HTML><HEAD> Mold Propagation Simulation Mold Propagation Simulation <!-- function startCircles() { for(var i=0; i<document.applets.length; i++) { for(var i=0; i<document.applets.length; i++) { document.applets[i].startCircles(); } document.applets[i].startCircles(); }} function stopCircles() { for(var i=0; i<document.applets.length; i++) { for(var i=0; i<document.applets.length; i++) { document.applets[i].stopCircles(); } document.applets[i].stopCircles(); }} // --> // --> </HEAD>
38
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.38 Controlling Applets from JavaScript, Example RandomCircles.java RandomCircles.java public class RandomCircles extends Applet implements Runnable { private boolean drawCircles = false; private boolean drawCircles = false; public void startCircles() { public void startCircles() { Thread t = new Thread(this); Thread t = new Thread(this); t.start(); t.start(); } public void run() { public void run() { Color[] colors = { Color.lightGray, Color.gray, Color.darkGray, Color.black }; Color[] colors = { Color.lightGray, Color.gray, Color.darkGray, Color.black }; int colorIndex = 0; int colorIndex = 0; int x, y; int x, y; int width = getSize().width; int width = getSize().width; int height = getSize().height; int height = getSize().height; Graphics g = getGraphics(); Graphics g = getGraphics(); drawCircles = true; drawCircles = true;......
39
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.39 Controlling Applets from JavaScript, Example RandomCircles.java RandomCircles.java public class RandomCircles extends Applet implements Runnable { private boolean drawCircles = false; private boolean drawCircles = false; public void startCircles() { public void startCircles() { Thread t = new Thread(this); Thread t = new Thread(this); t.start(); t.start(); } public void run() { public void run() { Color[] colors = { Color.lightGray, Color.gray, Color.darkGray, Color.black }; Color[] colors = { Color.lightGray, Color.gray, Color.darkGray, Color.black }; int colorIndex = 0; int colorIndex = 0; int x, y; int x, y; int width = getSize().width; int width = getSize().width; int height = getSize().height; int height = getSize().height; Graphics g = getGraphics(); Graphics g = getGraphics(); drawCircles = true; drawCircles = true;......
40
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.40 Controlling Applets from JavaScript, Example RandomCircles.java, cont. RandomCircles.java, cont. while(drawCircles) { while(drawCircles) { x = (int)Math.round(width * Math.random()); x = (int)Math.round(width * Math.random()); y = (int)Math.round(height * Math.random()); y = (int)Math.round(height * Math.random()); g.setColor(colors[colorIndex]); g.setColor(colors[colorIndex]); colorIndex = (colorIndex + 1) % colors.length; colorIndex = (colorIndex + 1) % colors.length; g.fillOval(x, y, 10, 10); g.fillOval(x, y, 10, 10); pause(0.1); pause(0.1); } } public void stopCircles() { drawCircles = false; } public void stopCircles() { drawCircles = false; } private void pause(double seconds) { private void pause(double seconds) { try { Thread.sleep((int)(Math.round(seconds * 1000.0))); try { Thread.sleep((int)(Math.round(seconds * 1000.0))); } catch(InterruptedException ie) {} } catch(InterruptedException ie) {} }}
41
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.41 Controlling Applets from JavaScript, Results
42
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.42 Summary Applet operations are restricted Applet operations are restricted –Applet cannot read/write local files, call local programs, or connect to any host other than the one from which it was loaded The init method The init method –Called only when applet loaded, not each time executed –This is where you use getParameter to read PARAM data The paint method The paint method –Called each time applet is displayed –Coordinates in drawing operations are wrt top-left corner Drawing images Drawing images –getImage(getCodeBase(), "imageFile") to “ load ” –drawImage(image, x, y, this) to draw
43
INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.43 References CWP: Chapter 9 CWP: Chapter 9 http://java.sun.com/docs/books/tutorial/applet/ http://java.sun.com/docs/books/tutorial/applet/ http://www.echoecho.com/applets.htm http://www.echoecho.com/applets.htm The End. The End. Thank you for patience! Thank you for patience!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.