Learning Java/Applets

Simple example
The following example is made simple enough to illustrate the essential use of Java applets through its java.applet package.

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 &lt;APPLET&gt; or an &lt;OBJECT&gt; tag. For example:

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:

Applet inclusion is described in detail in Sun's official page about the APPLET tag. . 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.

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.

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.