1 Applets
1 Applets
1 Applets
Objectives
To define an applets To describe the support for applets by Java To see how applet differ from other application To understand the lifecycle of applet To implement applet
Applet is
Embedded java class in HTML and is downloaded and executed by web browser. Applets are not stand-alone programs, can run either by web browser or applet viewer How does it differ from an application? Executed by web browser Does not using main() method
It checks against a local file containing entries mapping special applets to special protection domain.
This enables special applet coming from particular places to run with special privileges
5
java.awt.Component java.awt.Container
java.awt.Window
java.awt.Panel
java.awt.Frame
java.applet.Applet
javax.swing.JApplet
7
Writing An Applet
import javax.swing.JApplet; Extends to Applet class
public class HelloWorld extends JApplet
Applet class must be public Its name must match the file name
Example : HelloWorld.java.
start()
Called when the applet become visible
paint(Graphics g)
Called when the component is exposed
stop()
Called when the applet become invisible
Browser is minimized or link follows to another URL
destroy()
Called when the browser is closed or exited
Loading An Applet
http://someLocation/file.html 1. The browser loads the URL
http://someLocation/file.html
Loading
10
init() after init start() exits destroy() return to page stop() Go to another page
11
Applet Display
Applets are graphical in nature. The browser environment calls the paint() method.
import java.awt.Graphics; import javax.swing.JApplet; public class HelloWorld extends JApplet { private int paintCount; public void init(){ paintCount = 0; } public void paint (Graphics g) { g.drawString("Hello World", 25,25); ++paintCount; g.drawString("Number of times paint called : " + paintCount, 25, 50); } } 12
Applet Display
HelloWorld.html <HTML> <applet code = "HelloWorld" width = 300 height = 100> </applet> </HTML>
13
Viewing Applet
Viewing using appletviewer
appletviewer HelloWorld.html
14
15
16
17
18
19
Example Code
import import import import java.awt.Graphics; java.awt.BorderLayout; javax.swing.JApplet; javax.swing.JFrame; public class HelloWorldApp extends JApplet { private int paintCount; public void init(){ paintCount = 0; }
public void paint (Graphics g) { g.drawString("Hello World", 25,25); ++paintCount; g.drawString("Number of times paint called : + paintCount, 25, 50); }
public static void main (String args[]) { JFrame frame = new JFrame("HelloWorldApp Demo"); HelloWorldApp app = new HelloWorldApp(); frame.add(app,BorderLayout.CENTER); app.init(); app.start(); frame.setSize(300,300); frame.setVisible(true); }
}
20
The End