Two Types of Applet
• Applet-
– These applets use the Abstract Window Toolkit (AWT) to
Applets , AWT Graphics, Color provide the graphic user interface (or use no GUI at all). This
style of applet has been available since Java was first created.
and Font Classes • JApplet-
– These are Swing applets and uses the Swing classes to
provide the GUI. Swing offers a richer and often easier-to-
use user interface than does the AWT. Thus, Swing-based
Sunita Tiwari applets are now the most popular. However, traditional
AWT-based applets are still used, especially when only a
very simple user interface is required. Thus, both AWT- and
Swing-based applets are valid
Applets Applet Support
• An applet is a Panel that allows interaction with a • Most modern browsers support Java 1.4 if they
Java program. have the appropriate plugin.
• A applet is typically embedded in a Web page and • In the PC labs, Internet Explorer 5.5 has been
can be run from a browser. updated, but Netscape has not.
• You need special HTML in the Web page to tell • The best support isn't a browser, but the
the browser about the applet. standalone program appletviewer (provided by
• For security reasons, applets run in a sandbox: JDK).
they have no access to the client’s file system. • In general you should try to write applets that can
be run with any browser.
What an applet is The Hirarchy of Applet
• You write an applet by extending the class Applet
• Applet is just a class like any other; you can even
use it in applications if you want java.lang.Object
• When you write an applet, you are only writing |
part of a program. +----java.awt.Component
|
• Execution of applet does not begin in main(). +----java.awt.Container
• Few applet may even have main() method but it |
does not start execution in main(). +----java.awt.Panel
|
+----java.applet.Applet
1
The simplest possible applet The simplest reasonable applet
/*<applet
code=“HelloWorld.class” width=150
height=100> It is member of
TrivialApplet.java </applet> */ the Graphics
import java.applet.Applet; class. Used to
import java.awt.*; write a message
public class TrivialApplet extends Applet { import java.applet.Applet; At x, y
} coordinate
public class HelloWorld extends Applet {
TrivialApplet.html public void paint( Graphics g ) {
g.drawString( "Hello World!", 30, 30 );
<applet }}
code="TrivialApplet.class”
width=150 height=100>
</applet>
3.3 Simple Java Applet: Drawing
How Applet Works
a String
• Running the applet in a Web browser (preferable write
applet tag in separate HTML file for browser)
Applet Class methods
How Applet Works Contd..
public void init () //This method is intended for whatever initialization is needed for
an applet.
public void start ()
//This method is automatically called after init method. It is also called whenever
user returns to the page containing the applet after visiting other pages.
public void stop ()
//This method is automatically called whenever the user moves away from the page
containing applets. This method can be used to stop an animation.
public void destroy ()
//This method is only called when the browser shuts down normally.
public void paint (Graphics)
Also:
public void repaint()
public void update (Graphics)
public void showStatus(String)
public String getParameter(String)
2
Why an applet works Applet Skeleton
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/* <applet code="AppletSkel" width=300 height=100> </applet> */
• You write an applet by extending the class Applet public class AppletSkel extends Applet {
// Called first.
• Applet defines methods init( ), start( ), stop( ), public void init() { // initialization
paint(Graphics), destroy( ) }
/* Called second, after init(). Also called whenever the applet is restarted. */
• These methods do nothing--they are stubs public void start() { // start or resume execution
}
• You make the applet do something by overriding // Called when the applet is stopped.
these methods. public void stop() { // suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() { // perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) { // redisplay contents of window
}}
public void init ( ) public void start ( )
• This is the first method to execute • Not always needed
• It is an ideal place to initialize variables • Called after init( )
• It is the best place to define the GUI Components • Called each time the page is loaded and restarted
(buttons, text fields, scrollbars, etc.), lay them out, • Used mostly in conjunction with stop( )
and add listeners to them • start() and stop( ) are used when the Applet is
• Almost every applet you ever write will have an doing time-consuming calculations that you don’t
init( ) method want to continue when the page is not in front
public void stop( ) public void destroy( )
• Not always needed • Seldom needed
• Called when the browser leaves the page • Called after stop( )
• Called just before destroy( ) • Use to explicitly release system resources (like
• Use stop( ) if the applet is doing heavy threads)
computation that you don’t want to continue when • System resources are usually released
the browser is on some other page automatically
• Used mostly in conjunction with start()
3
Methods are called in this order public void paint(Graphics g)
• init and destroy are only called
init() once each • Needed if you do any drawing or painting other than
• start and stop are called just using standard GUI Components
start() whenever the browser enters and • Any painting you want to do should be done here, or
leaves the page in a method you call from here
do some work • do some work is code called by • Painting that you do in other methods may or may not
your listeners happen
stop() • paint is called when the applet • Never call paint(Graphics), call repaint( )
needs to be repainted
destroy()
repaint( ) update( )
• When you call repaint( ), Java schedules a call to
• Call repaint( ) when you have changed something update(Graphics g)
and want your changes to show up on the screen
• Here's what update does:
• repaint( ) is a request--it might not happen
public void update(Graphics g) {
• When you call repaint( ), Java schedules a call to // Fills applet with background color, then
update(Graphics g) paint(g);
}
Painting at the right time is hard Other useful Applet methods
• Rule #1: Never call paint(Graphics g), call • System.out.println(String s)
repaint( ). – Works from appletviewer, not from browsers
• Rule #2: Do all your painting in paint, or in a – Automatically opens an output window.
method that you call from paint. • showStatus(String) displays the String in the
• Rule #3: If you paint on any Graphics other than applet’s status line.
the Applet’s, call its update method from the – Each call overwrites the previous call.
Applet’s paint method. – You have to allow time to read the line!
• Rule #4. Do your painting in a separate Thread.
• These rules aren't perfect, but they should help.
4
Simple Applet Display Methods Using Status Window
import java.awt.*;
• void setBackground(Color newColor) import java.applet.*;
/* <applet code="StatusWindow" width=300
• void setForeground(Color newColor) height=50>
• You can use the constants defined by Color class </applet> */
to specify colors: public class StatusWindow extends Applet{
public void init() {
• Example: Color.cyan , Color.pink Color.red etc setBackground(Color.cyan);
here. }
• setBackground(Color.green); // Display msg in applet window.
public void paint(Graphics g) {
• setForeground(Color.red); g.drawString("This is in the applet window.",
10, 20);
showStatus("This is shown in the status
window.");
}}
Applet tag Applet tag example
<APPLET <APPLETCODE=“test.class" CODEBASE="example/"
// the beginning of the HTML applet code WIDTH=460 HEIGHT=160 NAME="buddy" >
CODE="demoxx.class" <PARAMNAME="imageSource" VALUE="images/Beans">
// the actual name of the applet (usually a 'class' file) <PARAM NAME="backgroundColor" VALUE="0xc0c0c0">
CODEBASE="demos/" <PARAM NAME="endImage" VALUE=10> </APPLET>
// the location of the applet (relative as here, or a full URL)
NAME=“SWE622"
// the name of the instance of the appleton this page
WIDTH="100"
// the physical width of the applet on the page
HEIGHT="50"
//the physical height of the applet on the page
ALIGN="Top"
// align the applet within its page space (top, bottom, center)
<param name="arraysize" value="10"> Passing Parameter to Applet Tag
import java.awt.*; if(fontName == null) catch(NumberFormatException e) {
import java.applet.*; fontName = "Not Found"; leading = -1;
/* <applet code="ParamDemo" param = getParameter("fontSize"); }
width=300 height=80> try {
<param name=fontName param =
if(param != null) // if not found
• public String getParameter(String name) value=Courier>
fontSize = Integer.parseInt(param);
getParameter("accountEnabled
");
<param name=fontSize value=14>
<param name=leading value=2> else if(param != null)
<param name=accountEnabled fontSize = 0; active =
• String s = getParameter("arraysize"); value=true> </applet> */
public class ParamDemo extends
} catch(NumberFormatException e)
{
Boolean.valueOf(param).boolea
nValue();
Applet{ fontSize = -1; }
String fontName; // Display parameters.
int fontSize; }
• try { size = Integer.parseInt (s) } float leading; param = getParameter("leading"); public void paint(Graphics g) {
boolean active; try { g.drawString("Font name: " +
catch (NumberFormatException e) {…} // Initialize the string to be if(param != null) // if not found fontName, 0, 10);
displayed. leading = g.drawString("Font size: " +
public void start() { Float.valueOf(param).floatValu fontSize, 0, 26);
String param; e(); g.drawString("Leading: " + leading,
fontName = 0, 42);
getParameter("fontName"); else
leading = 0; g.drawString("Account Active: " +
active, 0, 58);
}
}
}
5
Output 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);
1 // WelcomeLines.java
2 // Displaying text and lines
3
4
5
// Java packages
import java.awt.*; // import class Graphics
Rectangles
6 import java.applet.*; // import class JApplet
7
8 public class WelcomeLines extends Applet {
import java.awt.*;
9 import java.applet.*;
10 // draw lines and a string on applet’s background
11 public void paint( Graphics g ) /*
12 {
<applet code="Rectangles" width=300
13
14 height=200>
15
</applet>
16 // draw horizontal line from (15, 10) to (210, 10)
17 g.drawLine( 15, 10, 210, 10 ); */
18
19 // draw horizontal line from (15, 30) to (210, 30) public class Rectangles extends Applet {
20 g.drawLine( 15, 30, 210, 30 ); Draw horizontal lines with public void paint(Graphics g) {
21 drawLine (endpoints have same
22 // draw String between lines at location (25, 25)
y coordinate). g.drawRect(10, 10, 60, 50);
23 g.drawString( "Welcome to Java Programming!", 25, 25 );
24
g.fillRect(100, 10, 60, 50);
25 } // end method paint g.drawRoundRect(190, 10, 60, 50, 15,
26
27 } // end class WelcomeLines
15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}}
Ellipse and Circle Arcs
// Draw Ellipses import java.awt.*;
import java.awt.*; import java.applet.*;
import java.applet.*; /*
/* <applet code="Arcs" width=300
<applet code="Ellipses" width=300 height=200>
height=200> </applet>
</applet> */
*/ public class Arcs extends Applet {
public class Ellipses extends Applet { public void paint(Graphics g) {
public void paint(Graphics g) { g.drawArc(10, 40, 70, 70, 0, 75);
g.drawOval(10, 10, 50, 50); g.fillArc(100, 40, 70, 70, 0, 75);
g.fillOval(100, 10, 75, 50); g.drawArc(10, 100, 70, 80, 0, 175);
g.drawOval(190, 10, 90, 30); g.fillArc(100, 100, 70, 90, 0, 270);
g.fillOval(70, 90, 140, 100); g.drawArc(200, 80, 80, 80, 0, 180);
} }
} }
6
Polygons Working with Color
import java.awt.*;
import java.awt.*; import java.applet.*;
g.setColor(c3);
g.drawLine(20, 150, 400, 40);
import java.applet.*; /* g.drawLine(5, 290, 80, 19);
<applet code="ColorDemo" width=300 g.setColor(Color.red);
/* height=200> g.drawOval(10, 10, 50, 50);
<applet code="HourGlass" width=230 </applet> g.fillOval(70, 90, 140, 100);
height=210> */ g.setColor(Color.blue);
public class ColorDemo extends Applet { g.drawOval(190, 10, 90, 30);
</applet> // draw lines g.drawRect(10, 10, 60, 50);
*/ public void paint(Graphics g) { g.setColor(Color.cyan);
Color c1 = new Color(255, 100, 100); g.fillRect(100, 10, 60, 50);
public class HourGlass extends Applet {
Color c2 = new Color(100, 255, 100); g.drawRoundRect(190, 10, 60, 50, 15, 15);
public void paint(Graphics g) { Color c3 = new Color(100, 100, 255); }
int xpoints[] = {30, 200, 30, 200, 30}; g.setColor(c1); }
g.drawLine(0, 0, 100, 100);
int ypoints[] = {30, 30, 200, 200, 30}; g.drawLine(0, 100, 100, 0);
int num = 5; g.setColor(c2);
g.drawLine(40, 25, 250, 180);
g.drawPolygon(xpoints, ypoints, num); g.drawLine(75, 90, 400, 400);
}
}
Getting the list of all available
Applet Security
Fonts
/*
<applet code="ShowFonts" width=550 • For security reasons, applets that are loaded over
height=60>
the network have several restrictions.
</applet>
*/ – an applet cannot ordinarily read or write files on the
import java.applet.*; computer that it's executing on.
import java.awt.*;
public class ShowFonts extends Applet { – an applet cannot make network connections except
public void paint(Graphics g) { to the host that it came from.
String msg = "";
String FontList[];
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironm
ent();
FontList = ge.getAvailableFontFamilyNames();
for(int i = 0; i < FontList.length; i++)
msg += FontList[i] + " ";
g.drawString(msg, 4, 16);
} }
Disadvantages of Applets Advantages of Applet
• Applets can’t run any local executable programs • Automatically integrated with HTML; hence, resolved virtually all
installation issues.
• Applets can’t with any host other than the originating
• Can be accessed from various platforms and various java-enabled web
server browsers.
• Applets can’t read/write to local computer’s file system • Can provide dynamic, graphics capabilities and visualizations
• Applets can’t find any information about the local • Implemented in Java, an easy-to-learn OO programming language
computer • Alternative to HTML GUI design
• All java-created pop-up windows carry a warning message • Safe! Because of the security built into the core Java language and the
applet structure, you don’t have to worry about bad code causing
• Stability depends on stability of the client’s web server damage to someone’s system
• Performance directly depend on client’s machine • Can be launched as a standalone web application independent of the
host web server
7
Applets are not magic!
• Anything you can do in an applet, you can do in
an application.
• You can do some things in an application that you
can’t do in an applet.
• If you want to access files from an applet, it must
be a “trusted” applet.
• Trusted applets are beyond the scope of this
subject.