JaVa
   

What Is an Applet?

Along with apps, we can also create applets. An applet is a Java program that is executed by the virtual machine within the confines of a web browser. Ever played a game in the web browser and wondered how it works? Well, the most likely culprit is a Java applet. When we create an applet, we use the JApplet class rather than the JFrame, and we need to structure the initial code slightly differently. The most important thing to note about the difference between apps and applets is the entry point; there is no main method in an applet. Let's look at a simple applet that will extend the JApplet class. An important point is that you must run an applet in a browser, as there is no other way to run it (except when developing/testing, you can use AppletViewer, which comes with the SDK). Here is a simple applet example:

A Simple Java Applet

Code Listing 8-3: Simple applet
import javax.swing.*;
public class MyApplet extends JApplet
{
 public void init()
 {
 setSize(400, 300);
 }
 public void start()
 {
 }
 public void stop()
 {
 }
 public void destroy()
 {
 }
}


Java End example

In addition, we can use the following HTML file (which we have called view.html) located in the same directory as the .class file to display the applet in the browser.

NoteĀ 

When developing, it is best to use the AppletViewer utility, which we will look at in the next section.

Code Listing 8-4: view.html (used to view the applet)
<HTML>
<HEAD>
 <TITLE>Simple Applet Example</TITLE>
</HEAD>
<BODY>
 <CENTER><B>Simple Applet Example</B>
 <BR>
 <APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=300></APPLET>
 </CENTER>
</BODY>
</HTML>


Java End example

When we compile the applet code and open the view.html file in a web browser, something similar to the following should be visible:

Java Click To expand
Screenshot-2: Our basic applet

If you do not know HTML, you can simply use this template and change the class filename appropriately, along with its width and height settings. For now, all you need to do is enter this into a text file and then save it as an .html file, which you may then load up using a web browser such as Internet Explorer. Let's now look at the code and see what we have done in more detail. This time around, we declare our main class so that it extends the JApplet class, which is part of the Swing package. This can be seen in the following line of code:

public class MyApplet extends JApplet


This is where applets differ from apps. For an app, we can create JFrame objects in various places, whereas with an applet the Java Virtual Machine is looking to create an instance of an applet class to begin with. Once we have defined our class to extend the JApplet, we can then override the methods important to the running of the applet and provide our own functionality for them. Let's look at each of these methods now and see what their purpose is. First we have the init method. This method is only called once when the applet is first loaded into the browser window and is used to initialize the applet. In our example, we set the size of the applet window in this method to 400x300 pixels. This can be seen in the following block of code:

public void init()
{
 setSize(400, 300);
}


NoteĀ 

Note that you may not set the size of the applet larger than defined in the HTML file. You can, however, make the applet smaller.

Next, we have the start method. This method is always called after the init method and can also be called if a browser window is minimized (or hidden) and then maximized again. However, this depends on the browser used, and therefore you should not depend on this happening. Then we have the stop method that again can be called by the browser window if it is minimized or hidden. As with the start method, this depends on the browser used when viewing the applet. Because we cannot depend on these methods being invoked by the browser when it is minimized, we can rely on other means. What we are looking at here from our point of view is the applet's loss of focus. We can handle the loss of focus differently in Java, as we shall see a little later on in the tutorial.

Finally, we have the destroy method, which is called when the applet is unloaded from the browser (i.e., the user has closed the browser window), where we can insert any code we need to clean up the program before it exits.

Viewing an Applet with AppletViewer

As well as being able to view the applet in a web browser, included within the Java SDK is a tool called AppletViewer, which allows you to view an applet without a web browser and can be useful for testing purposes, as some browsers have issues with caching applets. To use AppletViewer, you still need to create the .html file, as we did in the previous example, but instead of opening it in a browser, we pass it as a parameter to the AppletViewer tool. The command line can be seen here (which will work with the previous example):

C:\j2sdk1.4.1_01\bin\appletviewer view.html


When we run this command from the directory where our applets .class files are located (i.e., where it was compiled), we will see the following:

Java Click To expand
Screenshot-3: Our applet in AppletViewer

Specifying Program Arguments for Applets in HTML

A useful feature of applets is the ability to pass in parameters directly from HTML code. Let's look at a simple applet that takes in three parameters: a string followed by two numbers. It will then output the string and sum of the two numbers that were passed in. This is useful because it allows you to distribute your class files to other people without giving them the source code, but it allows them to add the applet to their site with some specific elements. For example, a parameter could specify the name of an image that the applet can then load in and display without changing any of the code but simply changing the HTML file under the user's control. Less work for programmers means happier programmers. The following example shows how we can specify parameters in the HTML file and then read them into our applet. Here is an HTML file and an applet that can read in the HTML parameter data:

Code Listing 8-5: view.html
<HTML>
<HEAD>
 <TITLE>Applet Parameter Passing Example</TITLE>
</HEAD>
<BODY>
 <CENTER><B>Applet Parameter Passing Example</B>
 <BR>
 <APPLET CODE="AppletParam.class" WIDTH=400 HEIGHT=300>
 <PARAM VALUE="Hello World">
 <PARAM VALUE=4>
 <PARAM VALUE=10>
 </APPLET>
 </CENTER>
</BODY>
</HTML>


Java End example
Code Listing 8-6: AppletParam.java
import java.awt.*;
import javax.swing.*;
public class AppletParam extends JApplet
{
 public void init()
 {
 setSize(400, 300);
 // Get and store the parameters...
 theString = getParameter("theString");
 number1 = Integer.parseInt(getParameter("Number1"));
 number2 = Integer.parseInt(getParameter("Number2"));
 }
 public void paint(Graphics g)
 {
 g.drawString("The string value was: "+theString, 20, 20);
 g.drawString("The first number was: "+String.valueOf
 (number1), 20, 40);
 g.drawString("The second number was: "+String.valueOf
 (number2), 20, 60);
 g.drawString("By adding the numbers we get: "+String.valueOf
 ((number1+number2)), 20, 80);
 }
 String theString;
 int number1;
 int number2;
}



Java End example

When we view the applet in the browser using the view.html file that we listed above, we should see something similar to the following figure.

Java Click To expand
Screenshot-4: Passing parameters to an applet

Now that we have looked at a working example, let's see how it works. This time we need to include both the AWT and Swing packages using the following two lines of code:

import java.awt.*;
import javax.swing.*;


We need to include the AWT package because in this example we have used the Graphics class to define the paint method for this class, as we will look at in a moment. In the init method, we grab the parameters supplied to us by the HTML page and store them in variables ready for drawing. We have defined three variables, as follows, in the main class to store this information:

String theString;
int number1;
int number2;


In order to get the values, we can use the getParameter method of our applet class to retrieve the three parameters, which are called theString, Number1, and Number2. This can be seen in the following few lines of code:

theString = getParameter("theString");
 number1 = Integer.parseInt(getParameter("Number1"));
 number2 = Integer.parseInt(getParameter("Number2"));


As you can see, we pass the name of the parameter to retrieve as a string to the getParameter method, and it then returns the value of the parameter as a string. Let's take a quick look at the HTML code that we used to pass the parameters in with now.

<APPLET CODE="AppletParam.class" WIDTH=400 HEIGHT=300>
 <PARAM VALUE="Hello World">
 <PARAM VALUE=4>
 <PARAM VALUE=10>
 </APPLET>


As can be seen in the above code, specify the parameters within the <APPLET> </APPLET> block using the <PARAM> tag. To specify the parameter, you need to have the NAME and its VALUE. Let's look at the theString one now:

<PARAM VALUE="Hello World">


So for this parameter, we have specified the name as theString and the value as Hello World. When we call the getParameter method in our applet, passing the string theString to it, it will return the string Hello World.

Finally, we have created a paint method, which is called by the browser every time the applet needs to be refreshed. Do not worry too much about this method now, as it will be explained in detail in . All this method does is output string values to the screen so that we can see the parameters have been passed in correctly.

Applet Security

One very important aspect of Java applets is security. A Java applet, even though it actually downloads and executes automatically on the user's machine, is restricted as to what it can do on the given machine. For example, an applet cannot write to the machine or connect to a network that the applet did not originate from; the applet can only connect to the server that it was downloaded from. Look at it this way: You open up a web page, and it has an applet. The applet then proceeds, running independently without your knowledge, to delete every file it finds on your computer (not ideal really). Therefore, applets require this security aspect for obvious reasons. If you really must gain access to the local file system or connect to another server from an applet which is not where the applet was downloaded from, you would require a signed applet.

Although creating signed applets is out of the scope of this tutorial, you can find information on it at the following link: http://java.oracle.com/products/jdk/1.1/docs/guide/security/.

JaVa
   
Comments