The Basic Applet Life Cycle
1.
The browser reads the HTML page
and finds any <APPLET> tags.
2.
The browser parses the
<APPLET> tag to find the CODE and possibly CODEBASE attribute.
3.
The browser downloads the .class
file for the applet from the URL found in the last step.
4.
The browser converts the raw
bytes downloaded into a Java class, that is a java.lang.Class object.
5.
The browser instantiates the
applet class to form an applet object. This requires the applet to have a
noargs constructor.
6.
The browser calls the applet's
init() method.
7.
The browser calls the applet's
start() method.
8.
While the applet is running, the
browser passes any events intended for the applet, e.g. mouse clicks, key
presses, etc., to the applet's handleEvent() method. Update events are used to
tell the applet that it needs to repaint itself.
9.
The browser calls the applet's
stop() method.
10.
The browser calls the applet's
destroy() method.
All applets have the following four methods:
public void init();
public void start(); public void stop(); public void destroy();
They have these methods because their superclass, java.applet.Applet,
has these methods
In the superclass, these are simply do-nothing methods. For example,
public
void init() {}
Subclasses may override these methods to accomplish certain tasks at
certain times. For instance, the init() method is a good place to read
parameters that were passed to the applet via <PARAM> tags because it's
called exactly once when the applet starts up
The start() method is called at least once in an applet's life, when the
applet is started or restarted. In some cases it may be called more than once.
Many applets you write will not have explicit start()methods and will merely
inherit one from their superclass. A start() method is often used to start any
threads the applet will need while it runs.
The stop() method is called at least once in an applet's life, when the
browser leaves the page in which the applet is embedded. The applet's start()
method will be called if at some later point the browser returns to the page
containing the applet. In some cases the stop() method may be called multiple
times in an applet's life. Many applets you write will not have explicit
stop()methods and will merely inherit one from their superclass.
The destroy() method is called exactly once in an applet's life, just
before the browser unloads the applet. This method is generally used to perform
any final clean-up.
Graphics Objects
In Java all drawing takes place via a Graphics object. This is an
instance of the class java.awt.Graphics. Initially the Graphics object you use
will be the one passed as an argument to an applet's paint() method.
Drawing Lines
Drawing straight lines with Java is easy. Just call
g.drawLine(x1,
y1, x2, y2)
where (x1, y1) and (x2, y2) are the endpoints of your lines and g is the
Graphics object you're drawing with.
This program draws a line diagonally across the applet.
import java.applet.*; import java.awt.*;
public class SimpleLine extends Applet {
public
void paint(Graphics g) {
g.drawLine(0, 0, this.getSize().width, this.getSize().height);
}
}
Drawing Rectangles
Drawing rectangles is simple. Start with a Graphics object g and call
its drawRect() method:
public void drawRect(int x, int
y, int width, int height)
As the variable names suggest, the first int is the left hand side of
the rectangle, the second is the top of the rectangle, the third is the width
and the fourth is the height. This is in contrast to some APIs where the four
sides of the rectangle are given.
This uses drawRect() to draw a rectangle around the sides of an applet.
import java.applet.*; import java.awt.*;
public class RectangleApplet extends Applet
{
public
void paint(Graphics g) {
g.drawRect(0, 0, this.getSize().width - 1, this.getSize().height
- 1);
} }
Remember that getSize().width is the width of the applet and
getSize().height is its height.
Clearing Rectangles
It is also possible to clear a rectangle that you've drawn. The syntax
is exactly what you'd expect:
public abstract void
clearRect(int x, int y, int width, int height)
This program uses clearRect() to blink a rectangle on the screen.
import java.applet.*; import java.awt.*;
public class Blink extends Applet {
public
void paint(Graphics g) {
int appletHeight = this.getSize().height; int appletWidth = this.getSize().width;
int rectHeight =
appletHeight/3;
int rectWidth = appletWidth/3;
int rectTop =
(appletHeight - rectHeight)/2;
int rectLeft =
(appletWidth - rectWidth)/2;
for (int i=0; i < 1000; i++) {
g.fillRect(rectLeft, rectTop, rectWidth-1,
rectHeight-1); g.clearRect(rectLeft, rectTop, rectWidth-1, rectHeight-1);
} } }
OVAL methods:
public void drawOval(int left,
int top, int width, int height) public void fillOval(int left, int top, int
width, int height)
Java also has methods to draw outlined and filled arcs. They're similar
to drawOval() and
fillOval() but you must also specify a starting and ending angle for the
arc. Angles are given in
degrees. The signatures are:
public void drawArc(int left, int
top, int width, int height, int startangle, int stopangle) public void
fillArc(int left, int top, int width, int height, int startangle, int
stopangle)
Polygons:
Polygons are defined by their corners. No assumptions are made about
them except that they lie in a 2-D plane. The basic constructor for the Polygon
class is
public Polygon(int[] xpoints, int[] ypoints, int npoints)
int[] xpoints = {0, 3, 0}; int[]
ypoints = {0, 0, 4};
Polygon myTriangle = new
Polygon(xpoints, ypoints, 3);
Loading Images
Images in Java are bitmapped GIF or JPEG files that
can contain pictures of just about anything. You can use any program at all to
create them as long as that program can save in GIF or JPEG format. If you know
the exact URL for the image you wish to load, you can load it with the
getImage() method:
URL imageURL = new
URL("http://www.prenhall.com/logo.gif"); java.awt.Image img =
this.getImage(imageURL);
Drawing Images at Actual Size
Once the image is loaded draw it in the paint() method using the
drawImage() method like this
g.drawImage(img,
x, y, io)
img is a member of the Image class which you should have already loaded
in your init() method. x is the x coordinate of the upper left hand corner of
the image.
y is the y coordinate of the upper left hand corner
of the image.
io is a member of a class which implements the
ImageObserver interface.
The ImageObserver interface is how Java handles the asynchronous
updating of an Image when it's loaded from a remote web site rather than
directly from the hard drive. java.applet.Applet implements ImageObserver so
for now just pass the keyword this to drawImage() to indicate that the current
applet is the ImageObserver that should be used.
A paint() method that does nothing more than draw an Image starting at
the upper left hand
corner of the applet may look like this
public void paint(Graphics g) {
g.drawImage(img, 0, 0, this);
}
import java.awt.*; import java.applet.*;
public class MagnifyImage extends Applet {
private Image image; private int scaleFactor;
public
void init() {
String filename
= this.getParameter("imagefile");
this.image = this.getImage(this.getDocumentBase(), filename); this.scaleFactor = Integer.parseInt(this.getParameter("scalefactor"));
}
public
void paint (Graphics g) {
int width = this.image.getWidth(this); int height = this.image.getHeight(this); scaledWidth = width * this.scaleFactor;
scaledHeight = height * this.scaleFactor;
g.drawImage(this.image,
0, 0, scaledWidth, scaledHeight, this);
} }
Color: color is a part of the Graphics object that does the drawing.
g.setColor(Color.pink);
g.drawString("This String is
pink!", 50, 25); g.setColor(Color.green);
g.drawString("This String is
green!", 50, 50);
Components
Components are graphical user interface (GUI) widgets like checkboxes, menus,
windows, buttons, text fields,
applets, and more. In Java
all components are subclasses of
java.awt.Component. Subclasses of Component include
·
Canvas
·
TextField
·
TextArea
·
Label
·
List
·
Button
·
Choice
·
Checkbox
·
Frame
·
JButton
·
JLabel
·
JComboBox
·
JMenu
Three Steps to Adding a Component
public void init() { Label l;
l = new Label("Hello Container");
this.add(l);
}
The key thing to remember about adding components to the applet is the
three steps:
1.
Declare the component
2.
Initialize the component
3.
Add the component to the layout.
import java.applet.*; import java.awt.*;
public class HelloContainer extends Applet { public void init() {
Label l;
l = new
Label("Hello Container"); this.add(l);
}
}
Here's a very simple applet with a Button:
import java.applet.*; import java.awt.*;
public class FirstButton extends Applet {
public
void init () {
this.add(new Button("My
First Button"));
} }
Button Actions
Unlike labels, buttons do things when you press them. When the mouse is
clicked on a Button, the Button fires an ActionEvent. To be ready to respond to
this event you must register an ActionListener
with the Button. For example,
Button beep = new Button("Beep");
add(beep); // add the button to the layout
beep.addActionListener(myActionListener); // assign the button a listener
Here myActionListener is a reference to an object which implements the
java.awt.event.ActionListener interface. This interface specifies a single
method, actionPerformed():
public abstract void actionPerformed(ActionEvent e)
The ActionListener object does something as a result of the ActionEvent
the button press fired. For example, the following class beeps when it gets an
ActionEvent:
import java.awt.*; import java.awt.event.*;
public class BeepAction implements ActionListener
{
public void actionPerformed(ActionEvent e) { Toolkit.getDefaultToolkit().beep();
} }
java.awt.Canvas
The java.awt.Canvas class is a rectangular area on which you can draw
using the methods of java.awt.Graphics. The Canvas class has only three
methods:
public Canvas()
public void addNotify()
public void paint(Graphics g)
You generally won't instantiate a canvas directly. Instead you'll
subclass it and override the paint() method in your subclass to draw the
picture you want.
For example the following Canvas draws a big red oval you can add to
your applet.
import java.awt.*;
public class RedOval extends Canvas { public void paint(Graphics g) {
Dimension d = this.getSize();
g.setColor(Color.red);
g.fillOval(0, 0, d.width,
d.height); }
public Dimension getMinimumSize() { return
new Dimension(50, 100); }
public Dimension getPreferredSize() { return
new Dimension(150, 300); }
public Dimension getMaximumSize() { return
new Dimension(200, 400); } }
Any applet that uses components should not also override paint(). Doing
so will have unexpected effects because of the way Java arranges components.
Instead, create a Canvas object and do your drawing in its paint() method.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.