Learning Java/Applets
< Learning Java
See also
Applets are Java programs that are used in Internet computing. They can be viewed using an applet viewer or any browser. An applet can perform functions like displaying graphics, animation, accept user input, etc. Applet is derived either from Applet or the newer JApplet class. Both inherit from Container, so if you know how to build JFrame or Frame (used in standalone applications), you largely know how to build the applet. Also, for many simple applets, it is common to just register the mouse listener on the same applet, call repaint() from mouse events when required and provide the paint(Graphics g) method to draw the applet how it must look at the given moment of time.
Applets are different from applications
They are not full featured application programs. They basically are developed for small tasks. There are many restrictions with applets.
  1. Applets do not use the main() method of Java (the traditional Java programs are required to do so). Method init() is called on startup and must setup the applet. The rest of activity usually happen in various event listeners, registered by init() on the applet components.
  2. Applets can not read or write to a local computer. This feature provides security to the applets from the local computer and to the local computer from applets.
  3. Applets can't communicate with other services of the network, apart the originating server.
  4. Applets can't use other language libraries like C and C++. Traditional programs can do so using so-called native methods.
Applet security restrictions can be lifted up by creating a so-called signed applet that verifies your identity through an independent authority server. However, it is complex and expensive to do this in a proper way, and if done wrongly (like self-signing) the signature can make the applet look untrustworthy.
Simple example
The following example is made simple enough to illustrate the essential use of Java applets through its java.applet package.
import java.applet.Applet​;​import java.awt.*;// Applet code for the "Hello, world!" example.// This should be saved in a file named as "HelloWorld.java".​public class HelloWorld extends Applet { // This method is mandatory, but can be empty (i.e., have no actual code). public void init() { } // This method is mandatory, but can be empty. public void stop() { } // Print a message on the screen (x=20, y=10). public void paint(Graphics g) { g.drawString("Hello, world!", 20,10); }}
For compilation, this code is saved on a plain-ASCII file (UTF-8 also works) with the same name as the class and .java extension, i.e. HelloWorld.java. The resulting HelloWorld.class applet should be installed on the web server and is invoked within an HTML page by using an <APPLET> or an <OBJECT> tag. For example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <​HTML​>​<​HEAD​>​<​TITLE​>​HelloWorld_example.html​</​TITLE​>​</​HEAD​>​<​BODY​>​<​H1​>​A Java applet example​</​H1​>​<​P​>​Here it is: <APPLET code​=​"HelloWorld.class" WIDTH="200" HEIGHT="40"> This is where HelloWorld.class runs.​</​APPLET​></​P​>​</​BODY​>​</​HTML​>
Displaying the HelloWorld_example.html page from a Web server, the result should look as this:
A Java applet example
Here it is: Hello, world!
To minimize download time, applets are usually delivered in a form of compressed zip archive (having jar extension). If all needed classes (only one in our case) are placed in compressed archive example.jar, the embedding code would look differently:
<P>Here it is: <APPLET code="HelloWorld" WIDTH="200" HEIGHT="40" ARCHIVE​=​"example.jar"​> This is where HelloWorld.class runs.</APPLET></P>
Applet inclusion is described in detail in Sun's official page about the APPLET tag.[1]. When you complete your first functional applet, you likely will want to share it somewhere. Unlike pictures, applets are currently not accepted in Wikipedia, but there are some alternative initiatives like Ultrastudio.org. Many applets are also deployed at SourceForge.net project pages. Of course, you can also have your own website, but there your applet may be more difficult to find.
Example with mouse listener
The following applet does all activities that majority of educational applets need: it responds to mouse clicks and drags and orders to repaint itself after the 100 ms in order to reflect the mouse manipulations. Applets can also interact with the keyboard, but this is less common. The applet below shows the mouse position in black if moved, in blue if dragged and repaints in red if clicked.
import java.applet.Applet​;​import java.awt.Color;import java.awt.Graphics​;​import java.awt.event.MouseEvent​;​import java.awt.event.MouseListener​;​import java.awt.event.MouseMotionListener​;​public class HelloMouse extends Applet implements MouseMotionListener​, MouseListener { // The "applet state" int x = -1; int y = -1; Color color = Color.BLACK; // Register mouse listener here. Mouse listeners can be the // same class as the applet if the listener methods // are added. public void init() { // Forwared mouse movements to mouseMoved, mouseDragged addMouseMotionListener​(​this​); // Forwared mouse clicks. addMouseListener​(​this​); } // This method is mandatory, but can be empty. public void stop() {} // Print a message on the screen (x=20, y=10). public void paint(Graphics g) { g.setColor(color); g.drawString("The mouse is at "+x+","+y, 20, 10); } public void mouseDragged​(​MouseEvent e) { x = e.getX(); y = e.getY(); color = Color.BLUE; repaint(100); // Repaint after 100 ms, } public void mouseMoved​(​MouseEvent e) { x = e.getX(); y = e.getY(); color = Color.BLACK; repaint(100); // Repaint after 100 ms, } } public void mouseClicked​(​MouseEvent e) { color = Color.RED; repaint(100); } public void mouseEntered​(​MouseEvent e) {} public void mouseExited​(​MouseEvent e) {} public void mousePressed​(​MouseEvent e) {} public void mouseReleased​(​MouseEvent e) {}}
Mouse listeners allow to detect not just the mouse manipulations but also when the mouse enters or leaves the applet area. The MouseEvent structure, that is passed to every method of the listener, contains information about the coordinates of the mouse pointer and also which button has been pressed.
Example with timer
The following example shows how register a timer to change applets on "its own initiative" after the programmed period of time. Timer is one of the basic elements of animations, non-interactive demonstrations and computer games. An applet can implement both ActionListener and mouse listeners, combining periodic actions with responses to the user manipulation.
import java.applet.Applet​;​import java.awt.Graphics​;​import java.awt.event.ActionEvent​;​import java.awt.event.ActionListener​;​import javax.swing.Timer​;​public class HelloTimer extends Applet implements ActionListener { // The "applet state" that advances up every second. int x = 0; Timer timer; // Register mouse listener here. Mouse listeners can be the // same class as the applet if the listener methods // are added. public void init() { // Create javax.swing.Timer that fires action events every second // The second parameter is the action listener. As this applet implements // ActionListener, we can pass "this" here. timer = new Timer(1000, this); timer.start(); } // This method is mandatory, but can be empty. public void stop() {} // Print a message on the screen (x=20, y=10). public void paint(Graphics g) { g​.​drawString​(​"Counting: "+x, 20, 10); } // This method is called by the timer. public void actionPerformed​(​ActionEvent e) { x = x + 1; repaint(10); // Repaint in 10 ms; }}
Events listener methods, called by javax.swing.Timer, run in a Swing thread. This means, it is safe to do Swing manipulations like setting texts for labels, etc., without using InvokeAndWait. Mind that there are more classes named "Timer" in other packages of Java system library, so be sure you are importing the right one.
Java.Sun.com Sun's APPLET tag page
See also
Interactive labs (Java applet)
Last edited on 19 April 2020, at 19:42
Content is available under CC BY-SA 3.0 unless otherwise noted.
Privacy policy
Terms of Use
HomeRandomLog inSettingsDonateAbout WikiversityDisclaimers