|
There are two goals for today's lesson. First, to understand the mechanics of a very simple applet. Second, to understand the common supporting HTML tags that enable an applet to be viewed by a web browser. A Simple Applet import java.applet.*; import java.awt.*; public class SimpleApplet extends Applet { public void paint (Graphics g) { setBackground(Color.blue); g.drawString(getParameter("message"), 50, 100); } } Code Explanation There are two libraries that must be imported for the applet to work: java.applet.* provides the Java program with the ability to be an applet and java.awt.* provides the program with the ability to do graphics. AWT is short for "Abstract Windowing Toolkit". Following the import statements, the first line of code states that the main class (SimpleApplet) is going to inherit methods from the Applet class. This is done through the "extends" syntax. The name of the file that this code is stored in must be called SimpleApplet.java since SimpleApplet is the name of the public class. There are many methods that can appear within an applet. Paint is the only one that is used for this simple example. The paint method takes the graphics context as a parameter and then proceeds to do the following two things. First, it sets the background color of the applet to blue through the built-in graphics method "setBackground" and the built-in graphics constant "Color.blue". Then, it displays the value of the HTML parameter "message" in position 50, 100 within the applet drawing area. The top, left coordinate of the drawing area is 0,0. Thus, the coordinate (50,100) is 50 pixels to the right of the top, left corner and then 100 pixels down from the top row. The "drawString" method is covered in more detail in the language reference summary regarding standard graphics. The Supporting HTML File <HTML> <TITLE>A Simple Applet</TITLE> <BODY> This applet displays a <APPLET CODE="SimpleApplet.class" CODEBASE="." WIDTH=200 HEIGHT=300 ALT="If you had a Java enabled browser, you would see a blue rectangle here."> <PARAM NAME=message VALUE="Simple Applet"> </APPLET> 200 pixel wide by 300 pixel tall rectangle. </BODY> </HTML> HTML Explanation HTML includes several tags that support applets. Looking at the code above, which is located in a file called "SimpleApplet.html", we see the following APPLET tags:
In addition to the tags that appear in the file above, there are some other tags that are occasionally useful. To learn more about these tags, you should consult a more complete reference or conduct experiments on your own.
What You'll See: |