Download presentation
Presentation is loading. Please wait.
Published byArleen Garrett Modified over 7 years ago
1
Topic: Applets Course : JAVA PROGRAMMING Paper Code: ETCS-307
Faculty : Dr. Prabhjot Kaur Associate Professor, Dept. of Information Technology 1
2
What Are Applets? An applet is a special Java program that can be embedded in HTML documents. It is automatically executed by (applet-enabled) web browsers. In Java, non-applet programs are called applications.
3
Application vs. Applet Application Applet
Trusted (i.e., has full access to system resources) Invoked by Java Virtual Machine (JVM, java), e.g., java HelloWorld Should contain a main method, i.e., public static void main(String[]) Applet 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.Applet
4
Java Applets Built using one of general definitions of applets
Applet class JAapplet class Java applets are usually graphical Draw graphics in a defined screen area Enable user interaction with GUI elements
5
Java Applet Classes Abstract Windowing Toolkit 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
6
Java Applets 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 When browser loads Web page containing applet Applet downloads into Web browser begins execution Can be tested using appletviewer program
7
ClassName is an object that will be a subclass of JApplet
Applet Declaration Syntax (note difference from application declaration) public class ClassName extends Japplet/Applet ClassName is an object that will be a subclass of JApplet
8
Body of an Applet Note there is no main() method in an applet
Japplet/Applet class provides other methods instead of a main method First method executed is the init() method
9
Graphics Coordinate (0,0) x height y width
10
Running An Applet import java.applet.Applet; import java.awt.Graphics;
public class HelloApplet extends Applet { public void paint (Graphics g) { g.drawString ("Hello. Welcome to",25,25); g.drawString ("Java Programming",25,40); } Enter this text into your Ready to Program editor Compile the Java code
11
Running An Applet Now create an .html file to run the applet
Save it as HelloApplet.html Make sure you save it in the same directory as the .java file <html> <applet code = "HelloApplet.class" width=275, height = 100> </applet> </html>
12
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.
13
Running An Applet Now create an .html file to run the applet
Save it as HelloApplet.html Make sure you save it in the same directory as the .java file <html> <applet code = "HelloApplet.class" width=275, height = 100> </applet> </html>
14
First Java Applet Java source in HelloWorldApplet.java
import java.awt.*; import java.applet.Applet; public class HelloWorldApplet extends Applet { public void paint(Graphics g) { Dimension d = getSize(); g.setColor(Color.BLACK); g.fillRect(0, 0, d.width, d.height); // paint background g.setFont(new Font("San-serif", Font.BOLD, 24)); g.setColor(new Color(255, 215,0)); g.drawString("Hello, world!", 60, 40); g.drawImage(getImage(getCodeBase(), “Rabbit.jpg"), 20, 60, this); } Represents graphics context, an abstraction of various drawing surfaces, e.g., screen, printer, off-screen image (an image stored in memory). Provide a rich set of graphics methods
15
Embedding Applet into HTML
HTML source in HelloWorld.html <!--HelloWorld.html--> <html> <head> <title>HelloWord</title> </head> <body> <center> <applet code="HelloWorldApplet.class" width=300 height=350></applet> </center> <hr/> <a href="HelloWorldApplet.java">The source.</a> </body> </html>
16
Compiling and Running To compile javac HelloWorldApplet.java
Produces HelloWorldApplet.class To run Open page HelloWorld.htmlfrom web browser or Use appletviewer of JDK appletviewer HelloWorld.html
17
The genealogy of Applet
java.lang.Object | +----java.awt.Component +----java.awt.Container +----java.awt.Panel +----java.applet.Applet +----Javax.swing.JApplet
18
Methods are called in this order
init() start() stop() destroy() do some work 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
19
Applet methods public void init () public void start ()
public void stop () public void destroy () public void paint (Graphics) Also: public void repaint() public void update (Graphics) public void showStatus(String) public String getParameter(String)
20
Applet Life Cycle
21
Why an applet works You write an applet by extending the class Applet.
Applet defines methods init( ), start( ), stop( ), paint(Graphics), destroy( ). These methods do nothing--they are stubs. You make the applet do something by overriding these methods.
22
public void init ( ) This is the first method to execute.
It is an ideal place to initialize variables. It is the best place to define the GUI Components (buttons, text fields, scrollbars, etc.), lay them out, and add listeners to them. Almost every applet you ever write will have an init( ) method.
23
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.
24
public void stop( ) Not always needed.
Called when the browser leaves the page. Called just before destroy( ). Use stop( ) if the applet is doing heavy computation that you don’t want to continue when the browser is on some other page. Used mostly in conjunction with start()
25
public void destroy( ) Seldom needed. Called after stop( ).
Use to explicitly release system resources (like threads). System resources are usually released automatically.
26
public void paint(Graphics g)
Needed if you do any drawing or painting other than just using standard GUI Components. Any painting you want to do should be done here, or in a method you call from here. Painting that you do in other methods may or may not happen. Never call paint(Graphics), call repaint( ).
27
repaint( ) Call repaint( ) when you have changed something and want your changes to show up on the screen repaint( ) is a request--it might not happen When you call repaint( ), Java schedules a call to update(Graphics g)
28
update( ) When you call repaint( ), Java schedules a call to update(Graphics g) Here's what update does: public void update(Graphics g) { // Fills applet with background color, then paint(g); }
29
Sample Graphics methods
A Graphics is something you can paint on g.drawString(“Hello”, 20, 20); Hello g.drawRect(x, y, width, height); g.fillRect(x, y, width, height); g.drawOval(x, y, width, height); g.fillOval(x, y, width, height); g.setColor(Color.red);
30
HTML <html> <head>
<title> Hi World Applet </title> </head> <body> <applet code="HiWorld.class” width=300 height=200> <param name="arraysize" value="10"> </applet> </body> </html>
31
<param name="arraysize" value="10">
HTML <param name="arraysize" value="10"> public String getParameter(String name) String s = getParameter("arraysize"); try { size = Integer.parseInt (s) } catch (NumberFormatException e) {…}
32
Adding two Floating point numbers.
Example 1 Adding two Floating point numbers.
33
Adding Floating-Point Numbers
// Fig. 3.13: AdditionApplet.java // Adding two floating-point numbers. 3 // Java packages import java.awt.Graphics; // import class Graphics import javax.swing.*; // import package javax.swing 7 public class AdditionApplet extends JApplet { double sum; // sum of values entered by user 10 // initialize applet by obtaining values from user public void init() { String firstNumber; // first string entered by user String secondNumber; // second string entered by user 16 double number1; // first number to add double number2; // second number to add 19 // obtain first number from user firstNumber = JOptionPane.showInputDialog( "Enter first floating-point value" ); 23 // obtain second number from user secondNumber = JOptionPane.showInputDialog( "Enter second floating-point value" ); 27 // convert numbers from type String to type double number1 = Double.parseDouble( firstNumber ); number2 = Double.parseDouble( secondNumber ); 31 * 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.
34
Adding Floating-Point Numbers
// add numbers sum = number1 + number2; 34 } // end method init 36 // draw results in a rectangle on applet’s background public void paint( Graphics g ) { // call superclass version of method paint super.paint( g ); 42 // draw rectangle starting from (15, 10) that is 270 // pixels wide and 20 pixels tall g.drawRect( 15, 10, 270, 20 ); 46 // draw results as a String at (25, 25) g.drawString( "The sum is " + sum, 25, 25 ); 49 } // end method paint 51 52 } // end class AdditionApplet drawRect takes the upper left coordinate, width, and height of the rectangle to draw. <html> <applet code = "AdditionApplet.class" width = "300" height = "65"> </applet> </html>
35
Adding Floating-Point Numbers
36
Adding Floating-Point Numbers
Lines 1-2: Comments Line 5: imports class Graphics import not needed if use full package and class name public void paint ( java.awt.Graphics g ) Line 6: specify entire javax.swing package * indicates all classes in javax.swing are available Includes JApplet and JOptionPane Use JOptionPane instead of javax.swing.JOptionPane * does not load all classes Compiler only loads classes it uses import java.awt.Graphics; // import class Graphics import javax.swing.*; // import package javax.swing
37
Adding Floating-Point Numbers
public class AdditionApplet extends JApplet { Begin class declaration Extend JApplet, imported from package javax.swing Field declaration Each object of class gets own copy of the field Declared in body of class, but not inside methods 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) double sum; // sum of values entered by user
38
Adding Floating-Point Numbers
double sum; // sum of values entered by user Primitive type double Used to store floating point (decimal) numbers Method init Normally initializes fields and applet class Guaranteed to be first method called in applet First line must always appear as above Returns nothing (void), takes no arguments Begins body of method init public void init() {
39
Adding Floating-Point Numbers
String firstNumber; // first string entered by user String secondNumber; // second string entered by user 16 double number1; // first number to add double number2; // second number to add Declare variables Two types of variables Reference variables (called references) 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 Primitive types (called variables) Contain one piece of data
40
Adding Floating-Point Numbers
String firstNumber; // first string entered by user String secondNumber; // second string entered by user 16 double number1; // first number to add double number2; // second number to add Distinguishing references and variables If type is a class name, then reference String is a class firstNumber, secondNumber If type a primitive type, then variable double is a primitive type number1, number2
41
Adding Floating-Point Numbers
firstNumber = JOptionPane.showInputDialog( "Enter first floating-point value" ); Method JOptionPane.showInputDialog Prompts user for input with string Enter value in text field, click OK If not of correct type, error occurs In Chapter 15 learn how to deal with this Returns string user inputs Assignment statement to string Lines 25-26: As above, assigns input to secondNumber
42
Adding Floating-Point Numbers
number1 = Double.parseDouble( firstNumber ); number2 = Double.parseDouble( secondNumber ); static method Double.parseDouble Converts String argument to a double Returns the double value Remember static method syntax ClassName.methodName( arguments ) Assignment statement sum an field, can use anywhere in class Not defined in init but still used sum = number1 + number2;
43
Adding Floating-Point Numbers
} // end method init Ends method init appletviewer (or browser) calls inherited method start start usually used with multithreading Advanced concept, in Chapter 16 We do not declare it, so empty declaration in JApplet used Next, method paint called Method drawRect( x1, y1, width, height ) Draw rectangle, upper left corner (x1, y1), specified width and height Line 45 draws rectangle starting at (15, 10) with a width of 270 pixels and a height of 20 pixels g.drawRect( 15, 10, 270, 20 );
44
Adding Floating-Point Numbers
g.drawString( "The sum is " + sum, 25, 25 ); Sends drawString message (calls method) to Graphics object using reference g "The sum is" + sum - string concatenation sum converted to a string sum can be used, even though not defined in paint field, can be used anywhere in class Non-local variable
45
Example - 2 To draw human face
46
Draw Human Face
47
Interactive Input How to load media and text
URL getDocumentBase() – Directory from which HTML file is loaded. URL getCodeBase() - Directory from which .class file is loaded. showDocument() – to load another file from current Applet getAppletContext() – to get current applet environment. AudipClip getAudioClip(URL u) – Returns an AudioClip object (play(), stop(), loop()) Image getImage(URL u) – Returns an image object Void showStatus(String str) – display str in status window
48
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() { AppletContext ac= getAppletContext(); URL url = getCodeBase(); try ac.showDocument( new URL(url + “Test.html”)); }catch(MalformedURLException e) { showStatus(“URL not found”);} }
49
Example- 3: To load another file from Applet
50
To create Digital Clock
Example-4 To create Digital Clock
51
Animation Applet --- Digital Clock
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Calendar; public class DigitalClock extends java.applet.Applet { <Fields> <Methods> }
52
Program Structure java.applet.Applet DigitalClock + start(): void
+ stop(): void + paint(g: Graphics) : void 1 javax.swing.Timer <<use>> java.util.Calendar <<use>> <<use>> java.awt java.awt.event
53
Field Declarations protected Timer timer; protected Font font =
new Font("Monospaced", Font.BOLD, 48); protected Color color = Color.GREEN;
54
Object Initialization
public DigitalClock() { timer = new Timer(1000, createTimerTickHandler()); } protected ActionListener createTimerTickHandler() return new ActionListener() public void actionPerformed(ActionEvent event) repaint(); };
55
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.
56
The paint() Method public void paint(Graphics g) {
Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); g.setFont(font); g.setColor(color); g.drawString(hour / 10 + hour % 10 + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10, 10, 60); }
57
Who Calls the paint()method?
Timer ticks and calls ActionListener.actionPerformed() ActionListener.actionPerformed()calls DigitalClock.repaint() DigitalClock.repaint() calls DigitalClock.paint() The paint() method is usually not called directly.
58
HTML Source <!-- DigitalClock.html --> <html> <head>
<title>Digital Clock Applet</title> </head> <body bgcolor=black> <h1>The Digital Clock Applet</h1><p> <applet code=DigitalClock.class width=250 height=80> </applet> <p><hr> <a href=DigitalClock.java>The source</a> </body> </html>
59
Thank You
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.