430 likes | 440 Views
Applets. Introduction. Applets are small Java programs that are embedded in HTML Web pages. An applet is a Java program that runs on a web page Applets can be run within any modern browser appletviewer is a program that can run applet
E N D
Introduction • Applets are small Java programs that are embedded in HTML Web pages. • An applet is a Java program that runs on a web page • Applets can be run within any modern browser • appletviewer is a program that can run applet • When browser loads a web page with java applet, the applet downloads into local machine and executes in the browser.
The Applet class • To create an applet, you must import the Applet class • This class is in the java.appletpackage • TheAppletclass contains code that works with a browser to create a display window • Capitalization matters! • applet and Applet are different names
Importing the Applet class • Here is the directive that you need: import java.applet.Applet; • import is a keyword • java.applet is the name of the package • A dot ( .) separates the package from the class • Applet is the name of the class • There is a semicolon ( ; ) at the end
public class Drawing extends Applet { …we still need to put some code in here... }
public class Drawing extends Applet { public void paint(Graphics g) { g.drawString( "Hello World!", 30, 30 ); } }
The paint method • paint needs to be told where on the screen it can draw • This will be the only parameter it needs • public void paint(Graphics g) { … } • public says that anyone can use this method • void says that it does not return a result
The applet so far import java.applet.Applet;import java.awt.*;
Thejava.awtpackage • “awt” stands for “Abstract Window Toolkit” • The java.awt package includes classes for: • Drawing lines and shapes • Drawing letters • Setting colors • Choosing fonts • If it’s drawn on the screen, then java.awt is probably involved!
import java.applet.Applet; public class TrivialApplet extends Applet { ……………. }
The simplest possible applet /*<applet code="TrivialApplet.class” width=150 height=100> </applet>*/ import java.applet.Applet; public class TrivialApplet extends Applet { ……………. }
The simplest reasonable applet import java.awt.*; import java.applet.Applet; /*<applet code="TrivialApplet.class” width=150 height=100> </applet>*/ public class HelloWorld extends Applet { public void paint( Graphics g ) { g.drawString( "Hello World!", 30, 30); } }
The java.awtpackage defines a class named Color There are 13 predefined colors—here are their fully-qualified names: For compatibility with older programs (before the naming conventions were established), Java also allows color names in lowercase: Color.black, Color.darkGray, etc. Colors Color.BLACK Color.PINK Color.GREENColor.DARK_GRAY Color.RED Color.CYANColor.GRAY Color.ORANGE Color.BLUEColor.LIGHT_GRAY Color.YELLOWColor.WHITE Color.MAGENTA
New colors • Every color is a mix of red, green, and blue • You can make your own colors:new Color(red,green,blue) • Amounts range from 0 to 255 • Black is (0, 0, 0), white is (255, 255, 255) • Yellow is red + green, or (255, 255, 0)
The paint method so far public void paint(Graphics g) { g.setColor(Color.BLUE);…draw a rectangle… g.setColor(Color.RED);…draw another rectangle… setBackground(Color.black); setForeground(Color.red); }}
Some more java.awt methods • g.drawLine(x1 ,y1,x2 ,y2 ); • g.drawOval( left,top,width,height ); • g.fillOval( left,top,width,height); • g.drawRoundRect( left,top,width,height ); • g.fillRoundRect( left,top ,width,height); • g.drawArc( left,top,width,height,startAngle,arcAngle); • g.drawString(string,x,y);
Hello g.drawString(“Hello”, 20, 20); 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); Sample Graphicsmethods • A Graphicsis something you can paint on
HTML HEAD BODY (content) TITLE Structure of an HTML page • Most HTML tags are containers. • A container is <tag> to </tag>
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>
Embedding Applet in Web Page <HTML> <HEAD> <TITLE> Hello World Applet </TITLE> </HEAD> <body> <h1>Hi, This is My First Java Applet on the Web!</h1> <APPLET CODE="HelloWorldApplet.class" width=500 height=400> </APPLET> </body> </HTML>
Compiling and executing applet • First, you need to use the java compiler to compile the source code. • javac xxx.java • Second, embed your class name in the applet tag of a html page. • <applet code = “xxx.class” width = “300” height = “45”> • Use the java tool appletviewer to view and test your applet • appletviewer xxx.html • Use browser
Other useful Applet methods • System.out.println(String s) • Works from appletviewer, not from browsers • Automatically opens an output window. • showStatus(String) displays the String in the applet’s status line.
Applet Life Cycle • Every applet inherits a set of default behaviours from the Applet class. As a result, when an applet is loaded, it undergoes a series of changes in its state. The applet states include: • Initialisation – invokes init() • Running – invokes start() • Display – invokes paint() • Idle – invokes stop() • Dead/Destroyed State – invokes destroy()
Applet Life Cycle Diagram init() Born Begin stop() start() Running Idle destroy() paint() start() Dead End
public void init ( ) • init()is the first method to execute • It is an ideal place to initialize variables • If you are creating a GUI, init() 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
start( ), stop( ) and destroy( ) • 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 • public void start() is called: • Right after init( ) • Each time the page is loaded and restarted • public void stop( ) is called: • When the browser leaves the page • Just before destroy( ) • public void destroy( ) is called after stop( ) • Use destroy() to explicitly release system resources (like threads) • System resources are usually released automatically
init() start() do some work stop() destroy() Methods are called in this order • init and destroy are only called once each • start and stop are called whenever the browser enters and leaves the page • do some workis code called by your listeners • paint is called when the applet needs to be repainted
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), callrepaint( )
repaint( ) • Call repaint( ) when you have changed something and want your changes to show up on the screen • You do not need to call repaint() when something in Java’s own components (Buttons, TextFields, etc.) • You do need to call repaint() after drawing commands (drawRect(...), fillRect(...), drawString(...), etc.) • repaint( ) is a request--it might not happen • 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) • Here's what update does: • public void update(Graphics g) {// Fills applet with background color, then paint(g);}
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)
Passing Parameters to Applet <HTML> <HEAD> <TITLE> Hello World Applet </TITLE> </HEAD> <body> <h1>Hi, This is My First Communicating Applet on the Web!</h1> <APPLET CODE="HelloAppletMsg.class" width=500 height=400> <PARAM NAME="Greetings" VALUE="Hello Friend, How are you?"> </APPLET> </body> </HTML>
Applet Program Accepting Parameters //HelloAppletMsg.java import java.applet.Applet; import java.awt.*; public class HelloAppletMsg extends Applet { String msg; public void init() { msg = getParameter("Greetings"); if( msg == null) msg = "Hello"; } public void paint(Graphics g) { g.drawString (msg,10, 100); } } This is name of parameter specified in PARAM tag; This method returns the value of paramter.
Interactive Applets • Applets work in a graphical environment. Therefore, applets treats inputs as text strings. • We need to create an area on the screen in which use can type and edit input items. • We can do this using TextField class of the applet package. • When data is entered, an event is generated. This can be used to refresh the applet output based on input values.
Interactive Applet Program..(cont) //SumNumsInteractive..java import java.applet.Applet; import java.awt.*; public class SumNumsInteractive extends Applet { TextField text1, text2; public void init() { text1 = new TextField(10); text2 = new TextField(10); text1.setText("0"); text2.setText("0"); add(text1); add(text2); } public void paint(Graphics g) { int num1 = 0; int num2 = 0; int sum; String s1, s2, s3; g.drawString("Input a number in each box ", 10, 50); try { s1 = text1.getText(); num1 = Integer.parseInt(s1); s2 = text2.getText(); num2 = Integer.parseInt(s2); } catch(Exception e1) {}
Interactive Applet Program. sum = num1 + num2; String str = "THE SUM IS: "+String.valueOf(sum); g.drawString (str,100, 125); } public boolean action(Event ev, Object obj) { repaint(); return true; } }
The genealogy of Applet java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet
How Applets Differ from Applications • Although both the Applets and stand-alone applications are Java programs, there are certain restrictions are imposed on Applets due to security concerns: • Applets don’t use the main() method, but when they are load, automatically call certain methods (init, start, paint, stop, destroy). • They are embedded inside a web page and executed in browsers. • They cannot read from or write to the files on local computer. • They cannot communicate with other servers on the network. • They cannot run any programs from the local computer. • They are restricted from using libraries from other languages. • The above restrictions ensures that an Applet cannot do any damage to the local system.