java applets & graphics ine2720 web application software development essential materials
TRANSCRIPT
Java Applets & GraphicsJava Applets & Graphics
INE2720INE2720
Web Application Software Web Application Software DevelopmentDevelopment
Essential MaterialsEssential Materials
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
22
OutlineOutline
Applet restrictionsApplet restrictions Basic applet and HTML templateBasic applet and HTML template The applet life-cycleThe applet life-cycle Customizing applets through HTML Customizing applets through HTML
parametersparameters Methods available for graphical operationsMethods available for graphical operations Loading and drawing imagesLoading and drawing images Controlling image loadingControlling image loading Java Plug-In and HTML converterJava Plug-In and HTML converter Control Java from JavaScriptControl Java from JavaScript
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
33
Reviews: Java Reviews: Java LanguageLanguage Object-Oriented ProgrammingObject-Oriented Programming
– Objects, Class, Inheritance, InterfaceObjects, Class, Inheritance, Interface Language BasicsLanguage Basics
– Variables, Operators, ExpressionsVariables, Operators, Expressions– Flow control, LoopsFlow control, Loops
Object BasicsObject Basics– Create, use, cleanup objectsCreate, use, cleanup objects
Interfaces and PackagesInterfaces and Packages
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
44
Applet RestrictionsApplet Restrictions
Do not read from the local (client) diskDo not read from the local (client) disk Do not write to the local (client) diskDo not write to the local (client) disk Do not open network connections other Do not open network connections other
than to the server from which the than to the server from which the applet was loadedapplet was loaded
Do not link to client-side C code or call Do not link to client-side C code or call programs installed on the browser programs installed on the browser machinemachine
Cannot discover private information Cannot discover private information about the userabout the user
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
55
Applet TemplateApplet Templateimport java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;publicpublic class AppletTemplate class AppletTemplate extends Appletextends Applet { { // Variable declarations.// Variable declarations. publicpublic void void initinit() {() { // Variable initializations, image loading, etc.// Variable initializations, image loading, etc. }} publicpublic void void paintpaint(Graphics g) {(Graphics g) { // Drawing operations.// Drawing operations. }}}}
Browsers cache applets: in Netscape, use Browsers cache applets: in Netscape, use Shift-RELOADShift-RELOAD to to force loading of new applet. In force loading of new applet. In IEIE, use , use Control-RELOADControl-RELOADCan use Can use appletviewerappletviewer for initial testing for initial testing
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
66
Applet HTML TemplateApplet HTML Template<html><head><html><head> <title>A Template for Loading <title>A Template for Loading
Applets</title>Applets</title></head></head><body><body><h1>A Template for Loading Applets</h1><h1>A Template for Loading Applets</h1><p><p><applet code="AppletTemplate.class" <applet code="AppletTemplate.class"
width=120 height=60>width=120 height=60> <b>Error! You must use a Java-enabled <b>Error! You must use a Java-enabled
browser.</b>browser.</b></applet></applet></body></body></html></html>
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
77
Applet ExampleApplet Exampleimport java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;
/** An applet that draws an image. *//** An applet that draws an image. */
publicpublic class JavaJump class JavaJump extends Appletextends Applet { { private Image jumpingJava; private Image jumpingJava; // Instance var declarations // Instance var declarations
herehere
publicpublic void void initinit() { () { // Initializations here// 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."); }}
publicpublic void void paintpaint(Graphics g) { (Graphics g) { // Drawing here// Drawing here g.drawImage(jumpingJava, 0, 50, this);g.drawImage(jumpingJava, 0, 50, this); }}}}
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
88
Applet Example, ResultApplet Example, Result<HTML><HTML><HEAD><HEAD> <TITLE>Jumping Java</TITLE><TITLE>Jumping Java</TITLE></HEAD></HEAD><BODY BGCOLOR="BLACK" TEXT="WHITE"><BODY BGCOLOR="BLACK" TEXT="WHITE"><H1>Jumping Java</H1><H1>Jumping Java</H1><P><P><APPLET CODE="JavaJump.class" <APPLET CODE="JavaJump.class" WIDTH=250 WIDTH=250 HEIGHT=335>HEIGHT=335> <B>Sorry, this example requires <B>Sorry, this example requires Java.</B>Java.</B></APPLET></APPLET></BODY></BODY></HTML></HTML>
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
99
Java ConsoleJava Console
Standard output, System.out.print, is sent to Standard output, System.out.print, is sent to the Java Consolethe Java Console– Navigator: open from Navigator: open from WindowWindow menu menu– Communicator: open from Communicator: open from CommunicatorCommunicator … … ToolsTools menu menu
– IE: open from IE: open from ViewView menu (enable from menu (enable from ToolsTools … … InternetInternet OptionsOptions … … AdvancedAdvanced screen) screen)
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1010
Applet Inheritance Applet Inheritance HierarchyHierarchy Applet class Applet class
derives from derives from the Abstract the Abstract Window Window Toolkit (AWT) Toolkit (AWT) hierarchy.hierarchy.
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1111
Applet Life CycleApplet Life Cycle
1.1. public void init()public void init() - Called when applet is first initialized - Called when applet is first initialized2.2. public void start()public void start()
– Called immediately after init and again revisited after browser Called immediately after init and again revisited after browser left page containing appletleft page containing applet
– Used to start animation threadsUsed to start animation threads
3.3. public void paint(Graphics g)public void paint(Graphics g)– Called by the browser after init and start, and again whenever Called by the browser after init and start, and again whenever
the browser redraws the screen, (typically when part of the the browser redraws the screen, (typically when part of the screen has been obscured and then reexposed)screen has been obscured and then reexposed)
– This method is where user-level drawing is placedThis method is where user-level drawing is placed– Inherited from Inherited from java.awt.Containerjava.awt.Container
4.4. public void stop()public void stop()– Called when the browser leaves the pageCalled when the browser leaves the page– Used to stop animation threadsUsed to stop animation threads
5.5. public void destroy()public void destroy()– Called when applet is killed (rarely used)Called when applet is killed (rarely used)
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1212
AWT Pre-Made UI AWT Pre-Made UI ComponentsComponents AWT supplies the following UI AWT supplies the following UI
components:components:– ButtonsButtons (java.awt.Button) (java.awt.Button)– CheckboxesCheckboxes (java.awt.Checkbox) (java.awt.Checkbox)– Single-line text fieldsSingle-line text fields
(java.awt.TextField)(java.awt.TextField)– MenusMenus (java.awt.MenuItem) (java.awt.MenuItem)– ContainersContainers (java.awt.Panel) (java.awt.Panel)– Lists Lists (java.awt.List)(java.awt.List)
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1313
Useful Applet MethodsUseful Applet Methods
getCodeBase, getDocumentBasegetCodeBase, getDocumentBase– The URL of the:The URL of the:
Applet fileApplet file - - getCodeBasegetCodeBase HTML fileHTML file - - getDocumentBasegetDocumentBase
getParametergetParameter– Retrieves the value from the associated HTML Retrieves the value from the associated HTML PARAMPARAM
elementelement getSizegetSize
– Returns the Returns the DimensionDimension (width, height) of the applet (width, height) of the applet getGraphicsgetGraphics
– Retrieves the current Retrieves the current GraphicsGraphics object for the applet object for the applet– The The GraphicsGraphics object does not persist across object does not persist across paintpaint
invocationsinvocations
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1414
Useful Applet Useful Applet Methods,Methods,(Continued)(Continued) showDocumentshowDocument (AppletContext method) (AppletContext method)
getAppletContext().showDocument(...)getAppletContext().showDocument(...)
– Asks the browser to retrieve and a display a Web Asks the browser to retrieve and a display a Web pagepage
– Can direct page to a named Can direct page to a named FRAMEFRAME cell cell showStatusshowStatus
– Displays a string in the status line at the bottom of Displays a string in the status line at the bottom of the browserthe browser
getCursor, setCursorgetCursor, setCursor– Defines the Defines the CursorCursor for the mouse, for example, for the mouse, for example, CROSSHAIR_CURSORCROSSHAIR_CURSOR, , HAND_CURSORHAND_CURSOR, , WAIT_CURSORWAIT_CURSOR
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1515
Useful Applet Useful Applet Methods,Methods,(Continued)(Continued) getAudioClipgetAudioClip playplay
– Retrieves an audio file from a remote location and Retrieves an audio file from a remote location and plays itplays it
– JDK 1.1 supports .au only. Java 2 also supports JDK 1.1 supports .au only. Java 2 also supports MIDI, .aiff and .wavMIDI, .aiff and .wav
getBackground, setBackgroundgetBackground, setBackground– Gets/sets the background color of the appletGets/sets the background color of the applet– SystemColorSystemColor class provides access to desktop colors class provides access to desktop colors
getForeground, setForegroundgetForeground, setForeground– Gets/sets foreground color of applet (default color of Gets/sets foreground color of applet (default color of
drawing operations)drawing operations)
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1616
HTML APPLET ElementHTML APPLET Element
<applet <applet codecode="..." ="..." widthwidth=xxx =xxx heightheight=xxx ...> =xxx ...>
... ...
</applet></applet>
Required AttributesRequired Attributes– CODECODE
Designates the filename of the Java class file to loadDesignates the filename of the Java class file to load Filename interpreted with respect to directory of Filename interpreted with respect to directory of
current HTML page (default) unless current HTML page (default) unless CODEBASECODEBASE is is suppliedsupplied
– WIDTH and HEIGHTWIDTH 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 Values can be given in pixels or as a percentage of
the browser window widththe browser window width
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1717
HTML APPLET Element,HTML APPLET Element,continuedcontinued Other AttributesOther Attributes
– ALIGN, HSPACE, and VSPACE ALIGN, HSPACE, and VSPACE Controls position and border spacing just like Controls position and border spacing just like IMGIMG
element (in pixels)element (in pixels)
– ARCHIVEARCHIVE Designates JAR file (zip file with .jar extension) Designates JAR file (zip file with .jar extension)
containing all classes and images used by appletcontaining all classes and images used by applet Save considerable time download multiple class Save considerable time download multiple class
filesfiles
– NAMENAME Names the applet for interapplet and JavaScript Names the applet for interapplet and JavaScript
communicationcommunication
– MAYSCRIPTMAYSCRIPT (nonstandard) (nonstandard) Permits JavaScript to control the appletPermits JavaScript to control the applet
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1818
Setting Applet Setting Applet ParametersParameters
<h1>Customizable HelloWWW Applet</h1><h1>Customizable HelloWWW Applet</h1>
<applet code="HelloWWW2.class" width=400 height=40><applet code="HelloWWW2.class" width=400 height=40> <param name="BACKGROUND" value="LIGHT"><param name="BACKGROUND" value="LIGHT"> <b>Error! You must use a Java-enabled browser.</b><b>Error! You must use a Java-enabled browser.</b></applet></applet>
<applet code="HelloWWW2.class" width=400 height=40><applet code="HelloWWW2.class" width=400 height=40> <param name="BACKGROUND" value="DARK"><param name="BACKGROUND" value="DARK"> <b>Error! You must use a Java-enabled browser.</b><b>Error! You must use a Java-enabled browser.</b></applet></applet>
<applet code="HelloWWW2.class" width=400 height=40><applet code="HelloWWW2.class" width=400 height=40> <b>Error! You must use a Java-enabled browser.</b><b>Error! You must use a Java-enabled browser.</b></applet></applet>
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
1919
Reading Applet Reading Applet ParametersParameters Use Use getParameter(name)getParameter(name) to retrieve the value of the to retrieve the value of the
PARAM element and the name argument is case sensitivePARAM element and the name argument is case sensitive
publicpublic void void init()init() { { Color background = Color.gray;Color background = Color.gray; Color foreground = Color.darkGray;Color foreground = Color.darkGray; String backgroundType = String backgroundType = getParametergetParameter("BACKGROUND");("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; }} } ...} ... }}}}
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2020
Reading Applet Reading Applet Parameters:Parameters:ResultResult
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2121
Useful Graphics Useful Graphics MethodsMethods drawString(string, left, bottom)drawString(string, left, bottom)
– Draws a string in the current font and color with the Draws a string in the current font and color with the bottom leftbottom left corner of the string at the specified location corner of the string at the specified location
– One of the few methods where the y coordinate refers One of the few methods where the y coordinate refers to the bottom of shape, not the top. But y values are to the bottom of shape, not the top. But y values are still with respect to the still with respect to the top lefttop left corner of the applet corner of the applet windowwindow
drawRect(left, top, width, height)drawRect(left, top, width, height)– Draws the outline of a rectangle (1-pixel border) in the Draws the outline of a rectangle (1-pixel border) in the
current colorcurrent color fillRect(left, top, width, height)fillRect(left, top, width, height)
– Draws a solid rectangle in the current colorDraws 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)Draws a 1-pixel-thick line from (x1, y1) to (x2, y2)
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2222
Useful Graphics Useful Graphics Methods,Methods,continuedcontinued drawOval, fillOvaldrawOval, fillOval
– Draws an outlined and solid oval, where the Draws an outlined and solid oval, where the arguments describe a rectangle that bounds the ovalarguments describe a rectangle that bounds the oval
drawPolygon, fillPolygondrawPolygon, fillPolygon– Draws an outlined and solid polygon whose points Draws an outlined and solid polygon whose points
are defined by arrays or a are defined by arrays or a PolygonPolygon (a class that (a class that stores a series of points)stores a series of points)
– By default, polygon is closed; to make an open By default, polygon is closed; to make an open polygon use the drawPolyline methodpolygon use the drawPolyline method
drawImagedrawImage– Draws an imageDraws an image– Images can be in JPEG or GIF (including GIF89A) Images can be in JPEG or GIF (including GIF89A)
formatformat
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2323
Graphics ColorGraphics Color
setColor, getColorsetColor, getColor– Specifies the Specifies the foreground colorforeground color prior to prior to
drawing operationdrawing operation– By default, the graphics object receives the By default, the graphics object receives the
foreground color of the windowforeground color of the window– AWT has 16 predefined colors (AWT has 16 predefined colors (Color.redColor.red, , Color.blueColor.blue, etc.) or create your own color,, etc.) or create your own color,new Color(r, g, b)new Color(r, g, b)
– Changing the color of the Changing the color of the GraphicsGraphics object object affects only the drawing that explicitly uses affects only the drawing that explicitly uses that that GraphicsGraphics object object
To make permanent changes, call the To make permanent changes, call the applet’sapplet’s setForegroundsetForeground method. method.
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2424
Graphics FontGraphics Font
setFont, getFontsetFont, getFont– Specifies the font to be used for drawing textSpecifies the font to be used for drawing text– Determine the size of a character through Determine the size of a character through FontMetrics FontMetrics (in Java 2 use (in Java 2 use LineMetricsLineMetrics))
– Setting the font for the Setting the font for the GraphicsGraphics object does not object does not persist to subsequent invocations of persist to subsequent invocations of paintpaint
– Set the font of the window (I.e., call the Set the font of the window (I.e., call the applet’sapplet’s setFontsetFont method) for permanent changes to the method) for permanent changes to the GraphicsGraphics object object
– In JDK 1.1, In JDK 1.1, only 5 fontsonly 5 fonts are available: are available: Serif Serif (aka(aka TimesRomanTimesRoman), ), SansSerif SansSerif (aka (aka HelveticaHelvetica), ), Monospaced Monospaced (aka(aka Courier Courier), ), DialogDialog, and , and DialogInputDialogInput
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2525
Graphics BehaviorGraphics Behavior
Browser calls Browser calls repaintrepaint method to request method to request redrawing of appletredrawing of applet– Called when applet first drawn or applet is hidden Called when applet first drawn or applet is hidden
by another window and then re-exposedby another window and then re-exposed
repaint()
update(Graphics g)
paint(Graphics g)
“sets flag”
Clears screen, Calls paint
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2626
Drawing ImagesDrawing Images
Register the Image (from Register the Image (from initinit))
Image image = Image image = getImagegetImage(getCodeBase(), "file");(getCodeBase(), "file"); Image image = Image image = getImagegetImage (url); (url);
– Loading is done Loading is done in a separate threadin a separate thread– If URL is absolute, then If URL is absolute, then trytry//catchcatch block is required block is required
Draw the image (from Draw the image (from paintpaint)) g.g.drawImagedrawImage(image, x, y, window);(image, x, y, window); g.g.drawImagedrawImage(image, x, y, w, h, window);(image, x, y, w, h, window);
– May draw partial image or nothing at allMay draw partial image or nothing at all– Use the applet (Use the applet (thisthis) for the ) for the windowwindow argument argument
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2727
Loading Applet Image Loading Applet Image from Relative URLfrom Relative URL
import java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;/** An applet that loads an image /** An applet that loads an image
from a relative URL. */from a relative URL. */public class JavaMan1 extends Applet public class JavaMan1 extends Applet
{{ private Image javaMan;private Image javaMan; public void init() {public void init() { javaMan = javaMan =
getImage(getCodeBase(), getImage(getCodeBase(), "images/Java-Man.gif");"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); }}}}
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2828
Loading Applet Image Loading Applet Image from Absolute URLfrom Absolute URLimport java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;import java.net.*;import java.net.*;...... private Image javaMan;private Image javaMan; public void init() {public void init() { try {try { URL imageFile =URL imageFile = new new
URL("http://www.corewebprogramming.com" +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"); }} }}
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
2929
Loading Images in Loading Images in ApplicationsApplicationsimport java.awt.*;import java.awt.*;import javax.swing.*;import javax.swing.*;
class JavaMan3 extends class JavaMan3 extends JPanel JPanel {{ private Image javaMan;private Image javaMan;
public JavaMan3() {public JavaMan3() { String imageFile = String imageFile =
System.getProperty("user.dir") +System.getProperty("user.dir") + "/images/Java-Man.gif";"/images/Java-Man.gif"; javaMan = javaMan = getToolkit().getImage(imageFile);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); }} ......
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3030
Loading Images in Loading Images in Applications Applications (Continued)(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, WindowUtilities.openInJFrame(panel, 380,
390);390); } } }} See Swing chapter for WindowUtilitiesSee Swing chapter for WindowUtilities
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3131
Java Plug-InJava Plug-In
Internet Explorer and Netscape (except Internet Explorer and Netscape (except Version 6) only support JDK 1.1Version 6) only support JDK 1.1
Plug-In provides support for the latest JDKPlug-In provides support for the latest JDK– http://java.sun.com/products/plugin/http://java.sun.com/products/plugin/– Java 2 Plug-In > 5 MbytesJava 2 Plug-In > 5 Mbytes
Requires modification of Requires modification of APPLETAPPLET element to element to support support OBJECTOBJECT element (IE) or element (IE) or EMBEDEMBED element (Netscape)element (Netscape)– Use HTML Converter to perform the Use HTML Converter to perform the
modificationmodification
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3232
Java Plug-In HTML Java Plug-In HTML ConverterConverter
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3333
Java Plug-In HTML Java Plug-In HTML ConverterConverter
““Navigator Navigator for Windows Only” conversionfor Windows Only” conversion
<<EMBEDEMBED type="application/x-java-applet;version=1.3" type="application/x-java-applet;version=1.3" CODE = "HelloWWW.class" CODEBASE = "applets" CODE = "HelloWWW.class" CODEBASE = "applets" WIDTH = 400 HEIGHT = 40WIDTH = 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">> <NOEMBED><NOEMBED> <B>Error! You must use a Java-enabled <B>Error! You must use a Java-enabled
browser.</B>browser.</B> </NOEMBED></NOEMBED></</EMBEDEMBED>>
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3434
Java Plug-In HTML Java Plug-In HTML ConverterConverter
““Internet ExplorerInternet Explorer for Windows and for Windows and Solaris” conversionSolaris” conversion
<<OBJECTOBJECT classid="clsid:8AD9C840-044E-11D1-B3E9- classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"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 = CODE VALUE = "HelloWWW.class" ><PARAM NAME = CODE VALUE = "HelloWWW.class" > <PARAM NAME = CODEBASE VALUE = "applets" ><PARAM NAME = CODEBASE VALUE = "applets" > <PARAM NAME="type" <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">VALUE="application/x-java-applet;version=1.3"> <PARAM NAME="scriptable" VALUE="false"><PARAM NAME="scriptable" VALUE="false"> <PARAM NAME = "BACKGROUND" VALUE ="LIGHT"><PARAM NAME = "BACKGROUND" VALUE ="LIGHT"> <B>Error! You must use a Java-enabled browser.</B><B>Error! You must use a Java-enabled browser.</B></</OBJECTOBJECT>>
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3535
Application: Accessing Application: Accessing Java from JavaScriptJava from JavaScript Calling Java Methods DirectlyCalling Java Methods Directly
– JavaScript can access Java variables and JavaScript can access Java variables and methods simply by using the fully qualified methods simply by using the fully qualified name. For instance:name. For instance:
java.lang.System.out.println("Hello java.lang.System.out.println("Hello Console");Console");
– Limitations:Limitations: Can’t perform operations forbidden to appletsCan’t perform operations forbidden to applets No try/catch, so can’t call methods that throw No try/catch, so can’t call methods that throw
exceptionsexceptions Cannot write methods or create subclassesCannot write methods or create subclasses
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3636
Controlling Applets Controlling Applets from JavaScript, from JavaScript, ExampleExample
MoldSimulation.html, cont.MoldSimulation.html, cont.
<BODY BGCOLOR="#C0C0C0"><BODY BGCOLOR="#C0C0C0"><H1>Mold Propagation Simulation</H1><H1>Mold Propagation Simulation</H1><APPLET CODE="RandomCircles.class" WIDTH=100 HEIGHT=75></APPLET><APPLET CODE="RandomCircles.class" WIDTH=100 HEIGHT=75></APPLET><P><P><APPLET CODE="RandomCircles.class" WIDTH=300 HEIGHT=75><APPLET CODE="RandomCircles.class" WIDTH=300 HEIGHT=75></APPLET></APPLET><P><P><APPLET CODE="RandomCircles.class" WIDTH=500 HEIGHT=75><APPLET CODE="RandomCircles.class" WIDTH=500 HEIGHT=75></APPLET></APPLET><FORM><FORM><INPUT TYPE="BUTTON" VALUE="Start Simulations“ <INPUT TYPE="BUTTON" VALUE="Start Simulations“
onClick="startCircles()"onClick="startCircles()">><INPUT TYPE="BUTTON" VALUE="Stop Simulations" <INPUT TYPE="BUTTON" VALUE="Stop Simulations" onClick="stopCircles()"onClick="stopCircles()">></FORM></FORM></BODY></BODY></HTML></HTML>
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3737
Controlling Applets Controlling Applets from JavaScript, from JavaScript, ExampleExample
MoldSimulation.htmlMoldSimulation.html
<HTML><HEAD><HTML><HEAD> <TITLE>Mold Propagation Simulation</TITLE><TITLE>Mold Propagation Simulation</TITLE><SCRIPT TYPE="text/javascript"><!--<SCRIPT TYPE="text/javascript"><!--function function startCirclesstartCircles() {() { 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 function stopCirclesstopCircles() {() { 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(); } }}}// --></SCRIPT>// --></SCRIPT></HEAD></HEAD>
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3838
Controlling Applets Controlling Applets from JavaScript, from JavaScript, ExampleExample RandomCircles.javaRandomCircles.java
public class RandomCircles extends Applet implements Runnable {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[] colors = { Color.lightGray, Color.gray, Color.darkGray,
Color.black };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; ......
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
3939
Controlling Applets Controlling Applets from JavaScript, from JavaScript, ExampleExample
RandomCircles.javaRandomCircles.java
public class RandomCircles extends Applet implements Runnable {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[] colors = { Color.lightGray, Color.gray, Color.darkGray,
Color.black };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; ......
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
4040
Controlling Applets Controlling Applets from JavaScript, from JavaScript, ExampleExample RandomCircles.java, cont.RandomCircles.java, cont.
while(while(drawCirclesdrawCircles) {) { 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() { public void stopCircles() { drawCircles drawCircles = false; }= 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) {} }}}}
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
4141
Controlling Applets Controlling Applets from JavaScript, from JavaScript, ResultsResults
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
4242
SummarySummary
Applet operations are restrictedApplet operations are restricted– Applet cannot read/write local files, call local programs, Applet cannot read/write local files, call local programs,
or connect to any host other than the one from which it or connect to any host other than the one from which it was loadedwas loaded
The init methodThe init method– Called only when applet loaded, not each time executedCalled only when applet loaded, not each time executed– This is where you use getParameter to read PARAM dataThis is where you use getParameter to read PARAM data
The paint methodThe paint method– Called each time applet is displayedCalled each time applet is displayed– Coordinates in drawing operations are wrt top-left Coordinates in drawing operations are wrt top-left
cornercorner Drawing imagesDrawing images
– getImage(getCodeBase(), "imageFile") to “load”getImage(getCodeBase(), "imageFile") to “load”– drawImage(image, x, y, this) to drawdrawImage(image, x, y, this) to draw
INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment
All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.
4343
ReferencesReferences
CWP: Chapter 9CWP: Chapter 9 http://java.sun.com/docs/books/tutorial/applet/http://java.sun.com/docs/books/tutorial/applet/ http://www.echoecho.com/applets.htmhttp://www.echoecho.com/applets.htm
The End.The End. Thank you for patience!Thank you for patience!