Topic Applets Course JAVA PROGRAMMING Paper Code ETCS307

  • Slides: 59
Download presentation
Topic: Applets Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur

Topic: Applets Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Associate Professor, Dept. of Information Technology prabhjot. kaur@msit. in UNIT-II Applets 1

What Are Applets? q An applet is a special Java program that can be

What Are Applets? q An applet is a special Java program that can be embedded in HTML documents. q It is automatically executed by (appletenabled) web browsers. q In Java, non-applet programs are called applications UNIT-II Applets 2

Application vs. Applet Ø Application ü ü ü Ø Trusted (i. e. , has

Application vs. Applet Ø Application ü ü ü Ø Trusted (i. e. , has full access to system resources) Invoked by Java Virtual Machine (JVM, java), e. g. , java Hello. World Should contain a main method, i. e. , public static void main(String[]) Applet ü ü ü UNIT-II Remote applets are Not trusted (i. e. , has limited access to system resource to prevent security breaches) Invoked automatically by the web browser Should be a subclass of class java. applet. Applets 3

Java Applets q Built using one of general definitions of applets class v JAapplet

Java Applets q Built using one of general definitions of applets class v JAapplet class v Applet q Java applets are usually graphical v Draw graphics in a defined screen area v Enable user interaction with GUI elements UNIT-II Applets 4

Java Applet Classes q Abstract Windowing Toolkit Ø Ø q AWT Earlier versions of

Java Applet Classes q Abstract Windowing Toolkit Ø Ø q AWT Earlier versions of Java Applet class is one of the AWT components Java Foundation Classes JFC Ø Extension to Java in 1997 Has a collection of Swing components for enhanced GUIs Ø Swing component classes begin with J Ø UNIT-II Applets 5

Java Applets q Applets are Java programs that can be embedded in HTML documents

Java Applets q Applets are Java programs that can be embedded in HTML documents To run an applet you must create a. html file which references the applet Ø Ready to Program also will run an applet Ø q When browser loads Web page containing applet Applet downloads into Web browser Ø begins execution Ø q Can UNIT-II be tested using appletviewer program Applets 6

Applet Declaration Ø Syntax (note difference from application declaration) public class Class. Name extends

Applet Declaration Ø Syntax (note difference from application declaration) public class Class. Name extends Japplet/Applet Class. Name is an object that will be a subclass of JApplet 7 UNIT-II Applets

Body of an Applet q Note there is no main() method in an applet

Body of an Applet q Note there is no main() method in an applet ü q Japplet/Applet class provides other methods instead of a main method First method executed is the init() method UNIT-II Applets 8

Graphics Coordinate (0, 0) x height y width UNIT-II Applets 9

Graphics Coordinate (0, 0) x height y width UNIT-II Applets 9

Running An Applet import java. applet. Applet; import java. awt. Graphics; public class Hello.

Running An Applet import java. applet. Applet; import java. awt. Graphics; public class Hello. Applet extends Applet { public void paint (Graphics g) { g. draw. String ("Hello. Welcome to", 25); g. draw. String ("Java Programming", 25, 40); } } • Enter this text into your Ready to Program editor • Compile the Java code UNIT-II Applets 10

Running An Applet q Now create an. html file to run the applet <html>

Running An Applet q Now create an. html file to run the applet <html> <applet code = "Hello. Applet. class" width=275, height = 100> </applet> </html> q Save it as Hello. Applet. html q Make sure you save it in the same directory as the. java file UNIT-II Applets 11

Running An Applet import allows us to use predefined classes (allowing us to use

Running An Applet import allows us to use predefined classes (allowing us to use applets and graphics, in this case). extends allows us to inherit the capabilities of class JApplet. Method paint is guaranteed to be called in all applets. Its first line must be defined as above. UNIT-II Applets 12

Running An Applet q Now create an. html file to run the applet <html>

Running An Applet q Now create an. html file to run the applet <html> <applet code = "Hello. Applet. class" width=275, height = 100> </applet> </html> q Save it as Hello. Applet. html q Make sure you save it in the same directory as the. java file UNIT-II Applets 13

First Java Applet q Java source in Hello. World. Applet. java import java. awt.

First Java Applet q Java source in Hello. World. Applet. java import java. awt. *; import java. applet. Applet; public class Hello. World. Applet extends Applet { public void paint(Graphics g) { Dimension d = get. Size(); g. set. Color(Color. BLACK); g. fill. Rect(0, 0, d. width, d. height); // paint background g. set. Font(new Font("San-serif", Font. BOLD, 24)); g. set. Color(new Color(255, 215, 0)); g. draw. String("Hello, world!", 60, 40); g. draw. Image(get. Code. Base(), “Rabbit. jpg"), 20, 60, this); } } UNIT-II Applets 14

Embedding Applet into HTML q HTML source in Hello. World. html <!--Hello. World. html-->

Embedding Applet into HTML q HTML source in Hello. World. html <!--Hello. World. html--> <html> <head> <title>Hello. Word</title> </head> <body> <center> <applet code="Hello. World. Applet. class" width=300 height=350></applet> </center> <hr/> <a href="Hello. World. Applet. java">The source. </a> </body> </html> UNIT-II Applets 15

Compiling and Running ü To compile javac Hello. World. Applet. java Produces Hello. World.

Compiling and Running ü To compile javac Hello. World. Applet. java Produces Hello. World. Applet. class Ø To run Ø ü ü UNIT-II Open page Hello. World. htmlfrom web browser or Use appletviewer of JDK appletviewer Hello. World. html Applets 16

The genealogy of Applet java. lang. Object | +----java. awt. Component | +----java. awt.

The genealogy of Applet java. lang. Object | +----java. awt. Component | +----java. awt. Container | +----java. awt. Panel | +----java. applet. Applet | +----Javax. swing. JApplet UNIT-II Applets

Methods are called in this order init() Ø start() Ø do some work Ø

Methods are called in this order init() Ø start() Ø do some work Ø stop() Ø destroy() UNIT-II init and destroy are only called once start and stop are called whenever the browser enters and leaves the page do some work is code called by your listeners paint is called when the applet needs to be repainted Applets

Applet methods public public Also: public UNIT-II void void init () start () stop

Applet methods public public Also: public UNIT-II void void init () start () stop () destroy () paint (Graphics) void repaint() void update (Graphics) void show. Status(String) String get. Parameter(String) Applets

Applet Life Cycle UNIT-II Applets 20

Applet Life Cycle UNIT-II Applets 20

Why an applet works You write an applet by extending the class Applet. q

Why an applet works You write an applet by extending the class Applet. q Applet defines methods init( ), start( ), stop( ), paint(Graphics), destroy( ). q These methods do nothing--they are stubs. q You make the applet do something by overriding these methods. q UNIT-II Applets

public void init ( ) This is the first method to execute. q It

public void init ( ) This is the first method to execute. q It is an ideal place to initialize variables. q It is the best place to define the GUI Components (buttons, text fields, scrollbars, etc. ), lay them out, and add listeners to them. q Almost every applet you ever write will have an init( ) method. q UNIT-II Applets

public void start ( ) Ø Ø Ø Not always needed. Called after init(

public void start ( ) Ø Ø Ø Not always needed. Called after init( ). Called each time the page is loaded and restarted. Used mostly in conjunction with stop( ). start() and stop( ) are used when the Applet is doing time-consuming calculations that you don’t want to continue when the page is not in front. UNIT-II Applets

public void stop( ) Not always needed. q Called when the browser leaves the

public void stop( ) Not always needed. q Called when the browser leaves the page. q Called just before destroy( ). q Use stop( ) if the applet is doing heavy computation that you don’t want to continue when the browser is on some other page. q Used mostly in conjunction with start() q UNIT-II Applets

public void destroy( ) Seldom needed. q Called after stop( ). q Use to

public void destroy( ) Seldom needed. q Called after stop( ). q Use to explicitly release system resources (like threads). q System resources are usually released automatically. q UNIT-II Applets

public void paint(Graphics g) Needed if you do any drawing or painting other than

public void paint(Graphics g) Needed if you do any drawing or painting other than just using standard GUI Components. q Any painting you want to do should be done here, or in a method you call from here. q Painting that you do in other methods may or may not happen. q Never call paint(Graphics), call repaint( ). q UNIT-II Applets

repaint( ) Call repaint( ) when you have changed something and want your changes

repaint( ) Call repaint( ) when you have changed something and want your changes to show up on the screen q repaint( ) is a request--it might not happen q When you call repaint( ), Java schedules a call to update(Graphics g) q UNIT-II Applets

update( ) When you call repaint( ), Java schedules a call to update(Graphics g)

update( ) When you call repaint( ), Java schedules a call to update(Graphics g) q Here's what update does: public void update(Graphics g) { q // Fills applet with background color, then paint(g); } UNIT-II Applets

Sample Graphics methods q A Graphics is something you can paint on g. draw.

Sample Graphics methods q A Graphics is something you can paint on g. draw. String(“Hello”, 20); g. draw. Rect(x, y, width, height); g. fill. Rect(x, y, width, height); g. draw. Oval(x, y, width, height); g. fill. Oval(x, y, width, height); g. set. Color(Color. red); UNIT-II Applets Hello

HTML <html> <head> <title> Hi World Applet </title> </head> <body> <applet code="Hi. World. class”

HTML <html> <head> <title> Hi World Applet </title> </head> <body> <applet code="Hi. World. class” width=300 height=200> <param name="arraysize" value="10"> </applet> </body> </html> UNIT-II Applets

HTML <param name="arraysize" value="10"> ¡ public String get. Parameter(String name) ¡ String s =

HTML <param name="arraysize" value="10"> ¡ public String get. Parameter(String name) ¡ String s = get. Parameter("arraysize"); ¡ try { size = Integer. parse. Int (s) } catch (Number. Format. Exception e) {…} UNIT-II Applets

Example 1 Adding two Floating point numbers. UNIT-II Applets 32

Example 1 Adding two Floating point numbers. UNIT-II Applets 32

Adding Floating-Point Numbers 1 2 3 4 5 6 7 8 9 10 11

Adding Floating-Point Numbers 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 UNIT-II // Fig. 3. 13: Addition. Applet. java // Adding two floating-point numbers. // Java packages import java. awt. Graphics; import javax. swing. *; // import class Graphics // import package javax. swing public class Addition. Applet extends JApplet { double sum; // sum of values entered by user // initialize applet by obtaining values from user public void init() { String first. Number; // first string entered by user String second. Number; // second string entered by user double number 1; double number 2; // first number to add // second number to add // obtain first number from user first. Number = JOption. Pane. show. Input. Dialog( "Enter first floating-point value" ); // obtain second number from user second. Number = JOption. Pane. show. Input. Dialog( "Enter second floating-point value" ); // convert numbers from type String to type double number 1 = Double. parse. Double( first. Number ); number 2 = Double. parse. Double( second. Number ); Applets * allows any class in the package to be used. Field sum may be used anywhere in the class, even in other methods. Type double can store floating point numbers.

Adding Floating-Point Numbers 32 33 34 35 36 37 38 39 40 41 42

Adding Floating-Point Numbers 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 1 2 3 4 UNIT-II // add numbers sum = number 1 + number 2; } // end method init // draw results in a rectangle on applet’s background public void paint( Graphics g ) { // call superclass version of method paint super. paint( g ); // draw rectangle starting from (15, 10) that is 270 // pixels wide and 20 pixels tall g. draw. Rect( 15, 10, 270, 20 ); // draw results as a String at (25, 25) g. draw. String( "The sum is " + sum, 25 ); } // end method paint } // end class Addition. Applet draw. Rect takes the upper left coordinate, width, and height of the rectangle to draw. <html> <applet code = "Addition. Applet. class" width = "300" height = "65"> </applet> </html> Applets

Adding Floating-Point Numbers UNIT-II Applets 35

Adding Floating-Point Numbers UNIT-II Applets 35

Adding Floating-Point Numbers l 5 Lines 1 -2: Comments import java. awt. Graphics; l

Adding Floating-Point Numbers l 5 Lines 1 -2: Comments import java. awt. Graphics; l Line 5: imports class Graphics ¡ 6 import not needed if use full package and class name public void paint ( java. awt. Graphics g ) import javax. swing. *; l // import package javax. swing Line 6: specify entire javax. swing package ¡ * indicates all classes in javax. swing are available l l ¡ Includes JApplet and JOption. Pane Use JOption. Pane instead of javax. swing. JOption. Pane * does not load all classes l 36 UNIT-II // import class Graphics Compiler only loads classes it uses Applets

Adding Floating-Point Numbers 8 public class Addition. Applet extends JApplet { l Begin class

Adding Floating-Point Numbers 8 public class Addition. Applet extends JApplet { l Begin class declaration ¡ 9 Extend JApplet, imported from package javax. swing double sum; l // sum of values entered by user Field declaration Each object of class gets own copy of the field ¡ Declared in body of class, but not inside methods ¡ l l Variables declared in methods are local variables Can only be used in body of method Fields can be used anywhere in class ¡ Have default value (0. 0 in this case) ¡ 37 UNIT-II Applets

Adding Floating-Point Numbers 9 double sum; l Primitive type double ¡ 12 // sum

Adding Floating-Point Numbers 9 double sum; l Primitive type double ¡ 12 // sum of values entered by user Used to store floating point (decimal) numbers public void init() l Method init Normally initializes fields and applet class ¡ Guaranteed to be first method called in applet ¡ First line must always appear as above ¡ l 13 { l 38 UNIT-II Returns nothing (void), takes no arguments Begins body of method init Applets

Adding Floating-Point Numbers 14 15 16 17 18 l l String first. Number; String

Adding Floating-Point Numbers 14 15 16 17 18 l l String first. Number; String second. Number; // first string entered by user // second string entered by user double number 1; double number 2; // first number to add // second number to add Declare variables Two types of variables ¡ Reference variables (called references) l l l ¡ Primitive types (called variables) l 39 UNIT-II Refer to objects (contain location in memory) ¡ Objects defined in a class definition ¡ Can contain multiple data and methods paint receives a reference called g to a Graphics object Reference used to call methods on the Graphics object Contain one piece of data Applets

Adding Floating-Point Numbers 14 15 16 17 18 String first. Number; String second. Number;

Adding Floating-Point Numbers 14 15 16 17 18 String first. Number; String second. Number; // first string entered by user // second string entered by user double number 1; double number 2; // first number to add // second number to add l Distinguishing references and variables ¡ If type is a class name, then reference l l ¡ If type a primitive type, then variable l l 40 UNIT-II String is a class first. Number, second. Number double is a primitive type number 1, number 2 Applets

Adding Floating-Point Numbers 21 22 first. Number = JOption. Pane. show. Input. Dialog( "Enter

Adding Floating-Point Numbers 21 22 first. Number = JOption. Pane. show. Input. Dialog( "Enter first floating-point value" ); ¡ Method JOption. Pane. show. Input. Dialog Prompts user for input with string ¡ Enter value in text field, click OK ¡ l l If not of correct type, error occurs In Chapter 15 learn how to deal with this Returns string user inputs ¡ Assignment statement to string ¡ l 41 UNIT-II Lines 25 -26: As above, assigns input to second. Number Applets

Adding Floating-Point Numbers 29 30 number 1 = Double. parse. Double( first. Number );

Adding Floating-Point Numbers 29 30 number 1 = Double. parse. Double( first. Number ); number 2 = Double. parse. Double( second. Number ); l static method Double. parse. Double Converts String argument to a double ¡ Returns the double value ¡ Remember static method syntax ¡ l 33 sum = number 1 + number 2; l Assignment statement ¡ sum an field, can use anywhere in class l 42 UNIT-II Class. Name. method. Name( arguments ) Not defined in init but still used Applets

Adding Floating-Point Numbers 35 } // end method init l Ends method init appletviewer

Adding Floating-Point Numbers 35 } // end method init l Ends method init appletviewer (or browser) calls inherited method start ¡ start usually used with multithreading ¡ l l ¡ 45 Advanced concept, in Chapter 16 We do not declare it, so empty declaration in JApplet used Next, method paint called g. draw. Rect( 15, 10, 270, 20 ); l Method draw. Rect( x 1, y 1, width, height ) Draw rectangle, upper left corner (x 1, y 1), specified width and height ¡ Line 45 draws rectangle starting at (15, 10) with a width of 270 pixels and a height of 20 pixels ¡ 43 UNIT-II Applets

Adding Floating-Point Numbers 48 g. draw. String( "The sum is " + sum, 25

Adding Floating-Point Numbers 48 g. draw. String( "The sum is " + sum, 25 ); l Sends draw. String message (calls method) to Graphics object using reference g ¡ "The sum is" + sum - string concatenation l ¡ sum can be used, even though not defined in paint l l 44 UNIT-II sum converted to a string field, can be used anywhere in class Non-local variable Applets

Example - 2 To draw human face UNIT-II Applets 45

Example - 2 To draw human face UNIT-II Applets 45

Draw Human Face UNIT-II Applets 46

Draw Human Face UNIT-II Applets 46

Interactive Input How to load media and text Ø Ø Ø Ø URL get.

Interactive Input How to load media and text Ø Ø Ø Ø URL get. Document. Base() – Directory from which HTML file is loaded. URL get. Code. Base() - Directory from which. class file is loaded. show. Document() – to load another file from current Applet get. Applet. Context() – to get current applet environment. Audip. Clip get. Audio. Clip(URL u) – Returns an Audio. Clip object (play(), stop(), loop()) Image get. Image(URL u) – Returns an image object Void show. Status(String str) – display str in status window UNIT-II Applets 47

Example- 3: To load another file from Applet import java. awt. *; import java.

Example- 3: To load another file from Applet import java. awt. *; import java. applet. *; import java. net. *; public class Acdemo extends Applet{ public void start() { Applet. Context ac= get. Applet. Context(); URL url = get. Code. Base(); try { ac. show. Document( new URL(url + “Test. html”)); }catch(Malformed. URLException e) { show. Status(“URL not found”); } } } UNIT-II Applets 48

Example- 3: To load another file from Applet UNIT-II Applets 49

Example- 3: To load another file from Applet UNIT-II Applets 49

Example-4 To create Digital Clock UNIT-II Applets 50

Example-4 To create Digital Clock UNIT-II Applets 50

Animation Applet --- Digital Clock import java. awt. *; java. awt. event. *; javax.

Animation Applet --- Digital Clock import java. awt. *; java. awt. event. *; javax. swing. *; java. util. Calendar; public class Digital. Clock extends java. applet. Applet { } UNIT-II <Fields> <Methods> Applets 51

Program Structure java. applet. Applet Digital. Clock 1 + start(): void + stop(): void

Program Structure java. applet. Applet Digital. Clock 1 + start(): void + stop(): void + paint(g: Graphics) : void <<use>> java. awt UNIT-II <<use>> javax. swing. Timer java. util. Calendar <<use>> java. awt. event Applets 52

Field Declarations protected Timer timer; protected Font font = new Font("Monospaced", Font. BOLD, 48);

Field Declarations protected Timer timer; protected Font font = new Font("Monospaced", Font. BOLD, 48); protected Color color = Color. GREEN; UNIT-II Applets 53

Object Initialization public Digital. Clock() { timer = new Timer(1000, create. Timer. Tick. Handler());

Object Initialization public Digital. Clock() { timer = new Timer(1000, create. Timer. Tick. Handler()); } protected Action. Listener create. Timer. Tick. Handler() { return new Action. Listener() { public void action. Performed(Action. Event event) { repaint(); } }; } 54 UNIT-II Applets

The start() and stop() Methods public void start() { timer. start(); } public void

The start() and stop() Methods public void start() { timer. start(); } public void stop() { timer. stop(); } § Start and stop the timer § Stopped timer will not consume CPU time. UNIT-II Applets 55

The paint() Method public void paint(Graphics g) { Calendar calendar = Calendar. get. Instance();

The paint() Method public void paint(Graphics g) { Calendar calendar = Calendar. get. Instance(); int hour = calendar. get(Calendar. HOUR_OF_DAY); int minute = calendar. get(Calendar. MINUTE); int second = calendar. get(Calendar. SECOND); g. set. Font(font); g. set. Color(color); g. draw. String(hour / 10 + hour % 10 + ": " + minute / 10 + minute % 10 + ": " + second / 10 + second % 10, 60); } UNIT-II Applets 56

Who Calls the paint()method? Ø Timer ticks and calls Action. Listener. action. Performed() Ø

Who Calls the paint()method? Ø Timer ticks and calls Action. Listener. action. Performed() Ø Action. Listener. action. Performed() calls Digital. Clock. repaint() calls Digital. Clock. paint() Ø The paint() method is usually not called directly. Ø UNIT-II Applets 57

HTML Source <!-- Digital. Clock. html --> <html> <head> <title>Digital Clock Applet</title> </head> <body

HTML Source <!-- Digital. Clock. html --> <html> <head> <title>Digital Clock Applet</title> </head> <body bgcolor=black> <h 1>The Digital Clock Applet</h 1><p> <applet code=Digital. Clock. class width=250 height=80> </applet> <p><hr> <a href=Digital. Clock. java>The source</a> </body> </html> UNIT-II Applets 58

Thank You UNIT-II Applets 59

Thank You UNIT-II Applets 59