Academic Java    Java Tutorial  >  Applets  >  JApplet

JApplet Example

Java JApplet EXAMPLE output Java JApplet EXAMPLE output Applets are applications that cannot run by themselves. They run in the context of a browser, or software such as an appletviewer, that provides the interface in which the applet will run.

From a programming point of view applet classes are extensions of the JApplet class, which is a panel that has four methods that can be overridden, namely init(), start(), stop(), and destroy(). Within JApplet each of these methods has an empty body. Because they are overriden they have the annotation type @Override.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// JApplet Example
import java.awt.*;
import javax.swing.*;

class JAppletExample extends JApplet {

   @Override public void init() {
      System.out.println("init");
   }

   @Override public void start() {
      System.out.println("start");
   }

   @Override public void stop() {
      System.out.println("stop");
   }

   @Override public void destroy() {
      System.out.println("destroy");
   }

   @Override public void paint(Graphics g) {
      super.paint(g);
      g.drawString("A veil of mist lifted", 100, 150);
   }

}

7-9 The init() method is called once by a browser when the web page first creates the applet.
The method usually contains code to perform basic setup tasks. If you do not provide this method in your applet then the method in JApplet is run.

11-13 The start() method is always called whenever the applet becomes visible.
It is called immediately after the execution of init() on the first occasion, and then subsequently when the applet reappears after scrolling or browsing, for example.

15-17 The stop() method is always called by a browser whenever the applet becomes invisible. This allows any applet code producing effects such as animation to be stopped.

19-21 The destroy() method is called by a browser at some convenient point when it decides to remove the resources of the applet. It thus allows the applet a last chance to clean up before it is removed.

23-26 This applet provides a paint() method that draws on its panel.
This is called by the browser each time the panel's visible area is affected and is supplied with a Graphics object that facilitates drawing on its surface.
Because paint() overrides the superclass method, a call of super.paint() is advisable since it ensures that any other components of the superclass are painted.

25 The three parameters of the call to drawString() are the text of the string, and the x and y coordinates of where the string is to be displayed.
The x and y coordinates of where the string is to be displayed are actually the point of the baseline of the lefthand end of the string. Note that some characters, such as 'y', descend below the baseline.