Java was originally the first language that could run inside a web browser, this ability of java has made it famous and also allowed others to knock its programming prowess as it was deemed good for this purpose and this purpose only by some. The method that java used to run programs inside a web browser was by way of an applet.
A java applet is quite simply a program designed to run as part of a web page. When one encounters a java applet on the web, the applet is downloaded and begins running on the webpage. A good example of a java applet would be http://java.sun.com/...k/example1.html
(Ignore the code on that site for now, just focus on the clock example)
The applet itself is executed by the browser’s Java Virtual Machine (JVM).
Programming applets is rather different to coding a standard java program as the code must be adjusted to run on a webpage, this is most noticeable by not having a standard main method:
public static void main(String[] args)
as will be demonstrated later. An Applet also requires a HTML (Hyper Text Markup Language) page to be setup in order to have a webpage to run on.
A java applet is created firstly by making it a subclass of JApplet, which is a class in the Swing package (javax.swing). When you create a subclass of JApplet, your applet will have everything it needs to interact with a web browser and be run inside a HTML page. One would create a subclass of JApplet like so:
Import javax.swing.*; //make all classes from the swing package available
Public class Skeleton extends JApplet {
//Applet code will be coded in this method
}
Note: The subclass of JApplet must be public as JApplet is public however like normal, other class files that are used do not have to be.
A java applet has no standard main() method. Instead it has a series of methods that are there to handle various events that could occur in your applet. The most used methods/functions are:
- Init() and start(): These methods are called when the program is first loaded. Due to init() being called first, it is generally where programmers set up variables that are used.
- paint(): This method is required to display the various graphical elements of your applet. Should the programmer code something that requires for the applet to be redisplayed, then repaint() can be called. repaint() in simple terms refreshes the applet
- stop(): This method is called should the applet be stopped by the browser or the user.
- start(): This method is used to restart the method after it has been stopped.
- destroy(): This method is used to free the memory used by the java applet
The methods described above are automatically inherited by your JApplet class however none of these methods do anything as such. The programmer needs to code the above methods to fulfill their purposes described above. Not all the methods described above must be used in a Java Applet.
Our first Java Applet – Hello World:
import java.awt.*;
import javax.swing.*;
public class HelloWorld extends JApplet {
String message; //declare string greeting here so that it has scope to be used for both init() and paint() methods
public void init() { //automatically called when applet is started.
message = "Hello World!"; //set text of String message
}
public void paint (Graphics screen) { //called automatically by init() to draw graphical elements on the screen
Graphics2D screen2D = (Graphics2D) screen; //explained below code
screen2D.drawString(message, 25, 50); //explained below code
}
}
The first few lines are rather self-explanatory with the comments however the paint method is a little bit trickier. The paint() is called when something requires the applet to be refreshed. This “something” can be from the OS or the user using the browser itself. Say a user was to shrink the browser window, the paint() method must be called to shrink the applet’s graphical elements accordingly.
public void paint(Graphics screen) {
Graphics2D screen2D = (Graphics2D) screen;
The Graphics class is a “graphical context”, a “graphical context” is an environment in which something can be displayed. The screen object of the Graphics class in line 2 is cast into a Graphics2D object. The Graphics2D object is from the Swing package and it is necessary to do this to use the Swing methods associated with graphics. The Graphics and Graphics2D classes are from the java.awt.* package, you can import them via one of the following:
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.*;
screen2D.drawString(message, 25, 50);
The above line of code draws the String message onto the applet window:
- The first argument passed (message) handles the String to display.
- The second argument passed (25) handles the x position of the String to be displayed.
- The third argument passed (50) handles the y position of the String to be displayed.
Note: The (x,y) co-ordinate system of a Java Applet starts at the top right corner with (0,0), if you go to the right, the x co-ordinate increases and if you go down the y value increases.
Okay after that explanation, how do we display our code on a webpage?
In order to do this, a HTML page must be created. The code below is how we are going to test our java applet:
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<p>This is your first java applet shown below! </p>
<applet
code ="HelloWorld.class"
codebase="..\\..\\build\\classes"
height="150"
width="300"
<p>You need a java-enabled browser to see this.</p>
</applet>
</body>
</html>
If you are familiar with HTML then you can skip the brief HTML explanation below:
HTML’s commands are known as tags that are surrounded by < and > symbols. Tags starts with <tag> and end with </tag>. An example would be <body> and </body>. Tags are structured like follows:
<element attribute> </end of element>
A element is a browsing command. An attribute is the properties of the element that further instruct the browser. An example would be the applet tag
<applet
code ="HelloWorld.class"
codebase="..\\..\\build\\classes"
height="150"
width="300"
<p>You need a java-enabled browser to see this.</p>
</applet>
The first attribute of the applet tag (code) describes the name of the applet’s class file.
The second attribute (codebase) contains the path of the class file
The third attribute (height) sets the height of the applet in the browser window in terms of pixels.
The fourth attribute (width) sets the width of the applet in the browser window in terms of pixels.
The paragraph tag <p>You need a java-enabled browser to see this.</p> is only shown if the applet is unable to be run as the user’s browser does not have the java plug-in installed. </applet ends the applet tag.
Some basic and necessary tags to know in order to understand the HTML we will use for our applet are:
- <html> - Begins your HTML document.
- <head> - Contains information about the page such as the TITLE, META tags for proper Search Engine indexing, STYLE tags, which determine the page layout, and Javascript coding for special effects.
- <title> - The TITLE of your page. This will be visible in the title bar of the viewers’ browser.
- </title> - Closes the HTML <title> tag.
- </head> - Closes the HTML <head> tag.
- <body> - This is where you will begin writing your document and placing your HTML codes.
- </body> - Closes the HTML <body> tag.
- </html> - Closes the <html> tag.
(referenced from: http://www.web-sourc...odes_chart.htm)
If you wish to do more reading on HTML, see the Dream In Code tutorials or visit: http://www.web-sourc...codes_chart.htm
If you then save and run our HTML page for the HelloWorld Java Applet code above, you should get the following:

Now, that you have displayed your first Java applet.
You may be wondering how do you send and recieve parameters from a webpage so that you can work with your HTML document?
The way to do this is rather simple and it offers many benefits to your applet as your applet's results can depend upon the parameters in the web page. You would declare a parameter like so:
<param name="user" value ="Person">
The above code creates a parameter called viewer and sets its value to "Person".
Now that you have made the parameter, how then in Java can you receive the parameter from the webpage?
The solution to this is also simple, the java.awt.* package has a getParameter(String parameterName) method which will return the value of the entered parameter.
This would be achieved like so:
String userParameter = getParameter("user");
if (userParameter != null) { txtCurUser = userParameter; }
The reason for the above if statement is so that if the parameter is null or not found, we do nothing. If it is then we set our String value for txtViewer (Full listing below) and print the value of the HTML Parameter viewer.
Full listing for modified HelloWorld.java:
import java.awt.*;
import javax.swing.*;
public class HelloWorldModified extends JApplet {
String message; int txtCurUser;//declare string greeting here so that it has scope to be used for both init() and paint() methods
public void init() { //automatically called when applet is started.
message = "Hello World!"; //set text of greeting
String userParameter = getParameter("userAge");
if (userParameter != null) { txtCurUser = Integer.parseInt(userParameter); }
}
public void paint (Graphics screen) { //called automatically by init() to draw graphical elements on the screen
Graphics2D screen2D = (Graphics2D) screen;
screen2D.drawString(message, 25, 50);
screen2D.drawString("Age of person viewing this page:" + txtCurUser, 35, 70);
}
}
And the full text of the modified HelloWorld.html:
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<p>This is your java applet that handles parameters! </p>
<applet
code ="HelloWorldModified.class"
codebase="..\\..\\build\\classes"
height="150"
width="300">
<param name ="userAge" value="20">
<p>You need a java-enabled browser to see this.</p>
</applet>
</body>
</html>
I hope you have enjoyed my tutorial and that you now have a basic understanding of how Java Applets function and work
Challenge (for those new to Java Applets):
- Change the colour of the background of the HTML Page
- Create a java applet that displays Integer, String and Float Parameters.
Thanks,
v0rtex
This post has been edited by v0rtex: 30 April 2011 - 12:50 AM







MultiQuote








|