How to Create Interactive Web Programs with Java | 2 | WebReference

How to Create Interactive Web Programs with Java | 2

How to Create Interactive Web Programs with Java

Drawing in An Applet Window

Text is displayed in an applet window by using the drawString() method of the Graphics2D class, which draws text in a graphical user interface component. The drawString() method is similar in function to the System.out.println()method that displays information to the system's standard output device.

Before you can use the drawString() method, you must have a Graphics or Graphics2D object that represents the applet window.

The paint() method of all applets includes a Graphics object as its only argument, which can be cast to a Graphics2D object:

Graphics2D screen2D = (Graphics2D)screen;

When you have created a Graphics2D object like this, you can call its drawString() method to display text on the area represented by the object.

The following three arguments are sent to drawString():

  • The text to display, which can be several different strings and variables strung together with the + operator

  • The x position (in an (x,y) coordinate system) where the string should be displayed

  • The y position where the string should be displayed

The (x,y) coordinate system in an applet is used with several methods. It begins with the (0,0) point in the upper-left corner of the applet window. Figure 17.1 shows how the (x,y) coordinate system works in conjunction with the statement on Line 12 of SalutonApplet.java.

Testing the SalutonApplet Program

Although you have compiled the SalutonApplet program into a class file, you cannot run it using a Java interpreter such as java. If you do, you'll get an error message looking like this:

Exception in thread "main" java.lang.NoSuchMethodError: main

The error occurs because a Java interpreter runs applications by calling its main() method. Applets don't include this method. Instead, to run an applet, you need to create a web page that loads the applet. To create a web page, open up a new file on your word processor and call it SalutonApplet.html. Enter Listing 17.2 and then save the file.

All applets you write can be tested with the appletviewer tool that comes with the Java Development Kit. You can see the output of the SalutonApplet applet by typing the following:

appletviewer SalutonApplet.html

One thing to note about appletviewer is that it only runs the applets that are included in a web page, and does not handle any of the other elements such as text and images.

Applets can also be loaded by web browsers, if they are equipped with the Java Plug-in. To attempt this at a command line, type the following command:

SalutonApplet.html

You can also choose File, Open from the browser's menu to find and open the page.

Figure 17.2 shows a screen capture of SalutonApplet loaded in Mozilla Firefox.

If you can't get this applet to run in Firefox or another web browser, the most likely reason is that the browser needs the Java Plug-in.

The Java Plug-in

Though popular web browsers began including their own Java interpreters with the first release of the language in the mid-'90s, these interpreters failed to keep current.

To make it possible for Java 2 applets to run in current browsers, Sun Microsystems offers the Java Plug-in, a substitute for a browser's built-in interpreter that supports the most up-to-date version of the language.

A plug-in is a program that works in conjunction with a web browser to expand its functionality. Plug-ins handle a type of data that the browser normally could not handle. Apple offers a plug-in to display QuickTime movies, Macromedia distributes a plug-in to run Flash animation files, and many other kinds of special content are supported in this manner.

If you installed the Java Development Kit, you were given a chance to install the Java Plug-in at the same time.

The Java Plug-in runs Java applets in place of the web browser's Java interpreter. Once the Java Plug-in is installed, all future Java 2 applets will run automatically if they specify that the Plug-in should be used to run them.

The plug-in is part of the Java Runtime Environment, which can be downloaded at no cost from Sun's Java site at the address https://java.com.

Sending Parameters from a Web Page

Now that you have had some experience writing computer programs, you might be feeling one of the strongest emotions of the programmer: compiler angst. Even though it takes no more than 15 seconds to compile most programs, that time can seem interminable when you're debugging a program. Write, save, compile, Aargh—an error! Write, save, compile, Aargh! Write, save, compile, Aargh!… As this vicious cycle repeats itself, it's easy to become world-weary as a program is compiled and recompiled.

One of the driving forces behind parameter use in Java applets is the fear and loathing of compilation. Parameters enable you to change elements of an applet without editing or recompiling anything. They also make the program more useful.

Parameters are stored as part of the web page that contains an applet. They are created using the HTML tag param and its two attributes: name and value. You can have more than one param tag with an applet, but all of them must be between the opening <applet> tag and the closing </applet> tag, which also support parameters).

The following is an applet tag that includes several parameters:

<applet code=”ScrollingHeadline.class” height=”50” width=”400”>
<param name=”headline1” value=”Dewey defeats Truman”>
<param name=”headline2” value=”Stix nix hix pix”>
<param name=”headline3” value=”Man bites dog”>
</applet>

This example could be used to send news headlines to an applet that scrolls them across the screen. Because news changes all the time, the only way to create a program of this kind is with parameters.

You use the name attribute to give the parameter a name. This attribute is comparable to giving a variable a name. The value attribute gives the named parameter a value.

Receiving Parameters in the Applet

You have to do something in your Java program to retrieve the parameters on the web page or they will be ignored. The getParameter() method of the JApplet class retrieves a parameter from a param tag on a web page. The parameter name, which is specified with the name attribute on the page, is used as an argument to getParameter(). The following is an example of getParameter() in action:

String display1 = getParameter("headline1");

The getParameter() method returns all parameters as strings, so you have to convert them to other types as needed. If you want to use a parameter as an integer, you could use statements such as the following:

int speed;
String speedParam = getParameter(“speed”);
if (speedParam != null) {
     speed = Integer.parseInt(speedParam);
}

This example sets the speed variable by using the speedParam string. You have to test for null strings before setting speed because the parseInt() method cannot work with a null string. When you try to retrieve a parameter with getParameter() that was not included on a web page with the param tag, it will be sent as null, which is the value of an empty string.

Workshop: Handling Parameters in an Applet

The next project you'll undertake has little practical value, except perhaps as a taunting device. The ShowWeight applet takes a person's weight and displays it under several different units. The applet takes two parameters: a weight in pounds, and the name of the person who weighs that amount. The weight is used to figure out the person's weight in ounces, kilograms, and metric tons, all of which are displayed.

Create a new file with your word processor and give it the name ShowWeight.java. Enter Listing 17.3 into the file. Then save and compile the file.

The init() method is where the two parameters are loaded into the applet. Because they come from the web page as strings, they must be converted into the form you need: a floating-point number for the lbs variable, and a string for name.

Converting a string to a floating-point number requires two steps: converting the string to a Float object and then converting that object to a variable of the type float.

Lines 20–22 are used to convert the lbs variable into different units of measure. Each of these statements has (float) in front of the conversion equation. This is used to cast the result of the equation into a floating-point number.

The paint() method of the applet uses the drawString() method of the Graphics2D class to display a line of text onscreen. The paint() method has three arguments: the text to display, and the x and y positions where the text should be shown.

Before you can test the ShowWeight applet, you need to create a web page that contains the applet. Open up a new file on your word processor and name it ShowWeight.html. Enter Listing 17.4 and save it when you're done.

Use a web browser equipped with the Java Plug-in to see the ShowWeight applet. This demonstration uses Konishiki as its example because the American-born sumo wrestling champion weighs in at more than 605 pounds, making him the largest of these immodest, bikini-wearing behemoths. You can substitute anyone whose weight is either exemplary or well-known. Figure 17.3 shows an example of output from the applet. As you can see, Konishiki's workout regimen doesn't include a lot of fatfree SnackWell's Devil's Food Cakes.

To make the applet display a different name along with a different value for the weight parameter, all you have to change is the ShowWeight.html file. The applet itself will continue to work correctly.

Created: March 27, 2003
Revised: February 13, 2006

URL: https://webreference.com/programming/java_24/1