Developing Web-based Curricula Using Java Physlets

Wolfgang Christian, Davidson College
&
Aaron Titus, NC State University

Introduction

World Wide Web HTTP (HyperText Transmission Protocol) makes it possible to transmit multimedia-enhanced documents interactively in a platform independent fashion. HyperText Markup Language (HTML) documents are prepared and transmitted as text documents and can therefore be prepared with any text editor. Yet, the HTML browser displays full multimedia information such as text, graphics, video and sound. The recent introduction of the Java programming language by Sun Microsystems now makes it possible to add platform independent programs to this multimedia stew. Java accomplishes this trick by specifying a relatively simple Virtual Machine, VM, which can be implemented on any computer architecture, i.e., Unix, Mac, or Windows. Although this VM does not provide as rich a set of tools as the native operating system, the virtual machine can have a user interface with buttons, a drawing canvas, and other graphical elements. There may be virtue in simplicity. Small platform independent programs are ideally suited for instructional purposes such as homework problems. These applets can be embedded directly into HTML documents and can interact with the user using a scripting language such as JavaScript. This article demonstrates the use of Java applets in conjunction with JavaScript functions to deliver a wide variety of web-based interactive physics activities. Interested readers should consult recent Web Mechanics columns and the many excellent references and tutorials available on the web for a more complete discussion of HMTL and other web-based interactive technologies.

Java Technology

Preparing Java code to run inside a browser is a multi-step process. First write the code! After the code is written, the programmer compiles it into an intermediate state called a class file. These class files contain the "byte code" for the Java virtual machine. Finally, the main class file is embedded into an HTML document using the <APPLET> tag. This embedding is no different than adding a graphic to an HTML page with an <IMG> tag. Class files are downloaded into the browser along with other objects, such as sound files or GIF images, which are referenced within the containing HTML document. It is now up to the browser to lay out the page on the monitor and translate the machine independent class files into native binary code. It is the browser's job to provide the hooks into the operating system. Some browsers interpret and execute the Java one instruction at a time. This is a slow process and makes Java unsuitable for computation intensive tasks. Fortunately, browser vendors are now developing compilers that translate the entire class file into native machine code after downloading. These Just-In-Time, JIT, compilers have the potential of making Java almost as fast as C++ code. The shipping versions of Netscape Navigator and Microsoft Internet Explorer include such compilers.

It is not necessary to become a Java programmer in order to use Java applets in HTML documents. Many Java applets expose their most useful functions and procedures to the outside world-- in this case the browser-- thereby allowing the HTML author to use an applet in multiple contexts. The challenge is to find applets that allow the presentation of interesting physics in a pedagogically meaningful manner. We have named small scriptable applets that are capable of displaying physics content Physlets. Later in this paper we discuss the design, construction, use, and effectiveness of Physlets.

Embedding

The insertion of tags into the text document specifies the type and location of multimedia content. For example, the <IMG> tag can be used to insert a 300 by 250 pixel image of an apparatus into a document using the following syntax:

<IMG SRC="http://physics.davidson.edu/images/apparatus.gif" WIDTH="300" HEIGHT="250">.

Good WYSIWYG HTML editors are akin to the best word processors and hide these details from the author. The author simply does routine editing using cut and paste in order to insert images or highlighting to apply formatting and font styles. The finished document can be published on the web. Unfortunately, high-level integration of advanced interactive web-based technologies, such as JavaScript and Java, is still sketchy in most authoring packages. A passing knowledge of HTML syntax is usually required to develop interactive curricular material.

Fig. 1: Doppler Physlet as seen embedded into an HTML document.

Applets are embedded into web pages with a similar embedding paradigm. The author specifies the name of the applet and the size on the screen using the <APPLET> tag. For example, the Doppler Physlet shown in Figure 1 can be embedded within a web page using the following code:

<APPLET CODE="Doppler.class" WIDTH=320 HEIGHT=370> </APPLET>.

The applet is displayed by the browser and the user interacts with the applet using the applet's intrinsic controls. Doppler has a slider to set the velocity and a radio button to enable relativistic effects. In addition the user can use the mouse to make measurements on the wave fronts. The input burden is on the user. The HTML author assumes the user is knowledgeable in the operation of the applet.

Fig. 2: QTime Physlet as seen embedded into an HTML document.

A moderately complex applet may be prone to user error and frustration if too many parameters are presented on screen. Most HTML authors prefer to add parameter, <PARAM>, fields to the <APPLET> tag in order to set the default behavior. Each applet can have a unique set of parameter fields; the applet author should, of course, document them. Any applet can be embedded multiple times with different conditions in order to solve different physics problems. The QTime Physlet shown in Figure 2 has parameter fields to set the real and imaginary parts of the wave function as well as the potential. These fields can be used to set up the particle in a box, SHO, or barrier penetration problems. For example, in order to embed QTime within a web page and have it show the time evolution of a Gaussian wave packet within a square well we would need the following HTML code:

<APPLET CODE="QTime.class" WIDTH=320 height=370>
        <PARAM NAME="potential" VALUE="20*(step(1+x)-step(x-1))" >
        <PARAM NAME="real" VALUE="cos(2*pi*x)*exp(-(x+4)*(x+4))" >
        <PARAM NAME="imaginary" VALUE="sin(2*pi*x)*exp(-(x+4)*(x+4))" >
        <PARAM NAME="FPS" VALUE=10>
        <PARAM NAME="dt" VALUE=0.02>
        <PARAM NAME="numPts" VALUE=512>
        <PARAM NAME="minX" VALUE=-10>
        <PARAM NAME="maxX" VALUE=10>
        <PARAM NAME="showControls" VALUE=true>
        <PARAM NAME="helpFile" VALUE="SquareWellHelp.html" >
        <PARAM NAME="caption" VALUE="Square Well" >
</APPLET>

where FPS, frames per second, may need to be adjusted to produce smooth animation on less powerful computers. The Java programmer who designed the applet will usually provide default values for parameters so that it is often not necessary to assign each and every parameter. Although parameter fields spare the user from having to worry about many of the more arcane details of an applet, running the applet is far from foolproof. The tabbed panel in the QTime interface still allows a user to access (and change) the three function strings. This may be desirable for advanced students, but it is unlikely that a sophomore modern physics student needs to be confronted with the details of how to write the real and imaginary parts of a Gaussian wavefunction in atomic units with the appropriate momentum boost needed to produce a reasonable group velocity. The showControls parameter is designed to simplify the user interface and to hide these details. Setting this parameter to false hides the buttons at the bottom of the applet and the tabbed panel. Changing the wave function, as well as starting and stopping the animation, must now be done using a scripting language as explained in the following section.

Scripting

Scripting makes it possible to change the behavior of an embedded applet on the fly in ways that are just not possible using parameter tags. The user can still interact with the applet, but the interaction is controlled by the HTML author who adds the desired behavior using a language such as JavaScript or Visual Basic for Applications. For example, the Animator Physlet is designed to move a geometric shape inside an applet's bounding box along a predefined path, [x(t), y(t)]. Creating a 10-pixel diameter circle that follows a parabolic trajectory requires the following script:

document.animator.addCircle(10,"-10+6*t","-5+8*t-4.9t*t").

The usual "dot" notation of object oriented programming is used to invoke any of the applets’ public methods. Document refers to the HTML page containing the applet. Animator is the name given to the applet when it was embedded, and addCircle is the method name that is being invoked.

Although animation can certainly be accomplished using more sophisticated programs such as Interactive Physics or possibly even QuickTime movies, Applets written in the Physlets format offer some advantages. A typical Physlet is less than 100 kByte and downloads on a typical campus network in a few seconds. Applets download once per session, even if they are embedded on multiple pages. A few lines of script can change the behavior of a Physlet in preparation for another problem.

Pedagogically, Physlets are ideal for testing student misconceptions since they can be scripted to show unphysical behavior. Standard HTML form fields can be used so that students can easily change variables and observed the changed behavior. It is far more difficult to provide this type of interaction with any form of digital video.

The simplest way to execute a script is to assign the script to one of the predefined events of a standard HTML form element. For example, the following code will create two buttons on the HTML page. The first button will stop the Physlet animation while the second will reset the simulation time to zero.

<FORM NAME="Control">
        < INPUT TYPE ="button" VALUE ="Stop" onclick="document.Animator.stop( )">
        < INPUT TYPE ="button" VALUE ="Reset" onclick="document.Animator.reset(0.0)">
</FORM>

Although the above example could be expanded to invoke multiple JavaScript statements within a button's onclick method, more elaborate scripting is best accomplished with JavaScript functions. The following JavaScript function initializes the Animator applet for one of our interactive homework problems:

function prob1( ){
        document.Animator.deleteAll( );
        document.Animator.reset(0.0);
        document.Animator.setShapeRGB(255,0,0);
        document.Animator.addCircle(20,"0","20-10*t*t");
        document.Animator.setCaption("Constant Acceleration");
        document.Animator.setTimeInterval(0,2);
        document.Animator.forward( );
}

This script first clears the Animator Physlet of all geometric objects and sets time to zero. A red circle is then created which moves along the y axis with constant acceleration. Script can be written to create moving rectangles, polygons, arrows, and text, thereby allowing us to create a wide variety of physics problems with just one Physlet. More importantly, presenting students with visual, rather than textual, representation of information necessary to do a problem changes the problem solving strategy. It allows for different types of questions. What is the acceleration of the red ball? Are the laws of classical dynamics observed in the collision between the red and the blue balls? Which planet in the animation does not obey Kepler's laws? In problems such as these, the student must observe the motion and make appropriate measurements to obtain a solution.

Although JavaScript functions are part of an HTML page, a browser does not display them. They can most easily be invoked from within the containing page by using a variant of the familiar anchor tag.

<A HREF="JavaScript: prob1( )">Problem 1</a>

The phrase "Problem 1" will be highlighted in blue on the HTML page but clicking on this anchor will execute the function rather than providing the usual navigation to another page.

Java Code

Java is similar to C in some respects but its philosophy is much closer to Object Pascal. The following code shows a very simple applet that can be embedded and scripted from within an HTML page to display a text message. The paint(Graphics g) method draws a string near the center of the applet. It is invoked whenever the browser determines that the applet needs to be drawn. The applet also implements two methods to set and get the displayed message string.

import java.applet.*;
import java.awt.*;
public class Hello extends Applet
{
        private String message ="Hello World";

        public void init( ){
                this.setBackground(Color.white);
        }

        public void setMessage(String m){
                message=m;
                repaint( );
        }

        public String getMessage( ){return message;}

        public void paint(Graphics g){    // paint the string
                Rectangle r=this.bounds( );
                g.drawString(message, r.width/2, r.height/2);
        }

}

The visibility of variables and methods is controlled through the public and private keywords. For example the variable message is declared private and is not accessible from JavaScript (or from other Java classes.) Access to this variable is controlled by the accessor methods getMessage( ) and setMessage(String m). These methods can be invoked from JavaScript without any additional Java code using standard JavaScript syntax:

document.hello.setMessage("Another Message").

Notice that the setMessage code forces the applet to repaint the screen when the message is changed. Using methods to access private variables hides details of the implementation from the JavaScript programmer and is a key part of object oriented programming.

Although not required, the above applet follows the Java Beans specification for the naming of the two accessor methods. The Beans specification does not add any new Java syntax nor are Beans derived from any Java superclass. Java Beans are standard Java classes that conform to strict naming conventions so that the classes can communicate with other Beans using visual programming and authoring tools. Adding the words set and get to the variable named message allows the authoring package to display a dialog box that enables a developer to quickly access the applets public methods. The Bean is presented at a very high level of abstraction to the author. A physics instructor will be able to click, drag, and draw a bean-based Physlet onto a page and obtain a dialog box that displays a documented table of parameters and public methods. In the near future, it will be possible to draw a button and a QMTime Physlet onto an HTML page, drag a connection between these two objects, and connect the button's onclick( ) method to the Physlet's start( ) method. The authoring package will create the required JavaScript code the same way it creates the <IMG> tag when an image is dragged into a document.

Java has two important limitations as described in Paul Dubois' recent CIP Scientific Programming column. The first is speed. Although JIT compilers promise considerable speed improvements, it is likely that the added overhead incurred by array checking, garbage collection, and lack of pointer arithmetic will never allow Java to match well written Fortran or C code. Sun's recent announcement that the company will differentiate their JIT compilers based upon speed is not a good sign. Only the slow Sun JIT compiler will be free. However, the calculations necessary for most pedagogy do not require massive computation. Current Java technology is fast enough to solve the one dimensional time dependent Schroedinger equation using a 120 MHz Pentium. But programmers wishing to implement a three dimensional molecular dynamics simulation in Java will be disappointed.

The second limitation is Java's platform independence. In order to maintain both security and platform independence, Applets written in "pure Java" have restricted access to the local operating system. Pure Java applets cannot access Microsoft's Active X, Apple's QuickTime, or the local hard disk. Another problem is that the current Abstract Windows Toolkit, AWT, has a limited set of interface components. Modern components such as a tree-view or a tabbed panel are simply missing from the AWT. The tabbed panel that is used by Physlets was constructed from primitive AWT components. Its class file downloads with the applet. Although this approach is feasible, it leads to code bloat and other programming inefficiencies. Both Microsoft and Sun provide extensions to Java to address these problems. Unfortunately, the two company's solutions are likely to be incompatible. Since platform and vendor independence are important for pedagogy, we have attempted to find virtue in simplicity. Physlets are designed for scripting and have a minimal interface. Buttons, sliders, and a drawing panel are usually sufficient. Sophisticated interface components are avoided.

The good news about Java is that the core language is well-defined and unlikely to change. All major vendors and browser suppliers support the core language. Although speed, access to the local operating system, and user interface remain issues, other language features such as multithreading and network connectivity are built in and a pleasure to use. In short, Java technology is an excellent choice for the development of web-based curricular material.

Pedagogy

Physlets have been used to create multimedia-focused problems that are fundamentally different from traditional textbook physics problems. In multimedia-focused problems, information necessary to solve the problem is embedded in the animation rather than given in the text of the question. Students are then required to observe the motion, apply appropriate physics concepts, and make measurements before solving the problem mathematically. Such an approach is remarkably different than typical novice strategies where students attempt to mathematically analyze a problem before qualitatively describing it (an approach we as teachers often call "plug-and-chug" and characterized by the lack of conceptual thought during the problem solving process). Requiring students to consider the problem qualitatively, as is done in multimedia-focused problems, may have a positive influence on students’ problem solving skills and conceptual understanding.

Fig. 3: Animator Physlet scripted to display a sun and four planets.

For example, consider the Animator-Physlet problem shown in Figure 3. The student is asked to find the "planet" that does not obey Kepler's laws. How does a student solve this problem? The student must observe the motion and recognize that the ratio of the orbital period to the orbital radius is required for a number of planets. Numerous parameters must be observed and measured and it is unlikely that the first measurements will yield anything unexpected. In fact, the orbit that "looks" most unphysical is the outer orbit because the planet moves very slowly. The unphysical innermost planet zips along at too slow a rate. This visual representation of seemingly abstract formulas can be surprising to students.

How is the Physlet problem different from a similar traditional problem? In a traditional problem (see Gaincoli, Physics 5th ed, p 142), the student is given an orbital parameter for a satellite and is given another satellite for comparison, thereby suggesting the path to the solution. In comparison, the multimedia-focused problem requires observation and conceptual reasoning before quantitative analysis. Furthermore, the idea that the outer planets move very slowly in comparison to the inner planets is reinforced by visual observation.

Multimedia-focused problems are believed to be more "real-world-like" than traditional textbook problems. Upon first encountering multimedia-focused problems, many people comment that "they are like virtual laboratories." As in an experiment, students must determine what is required to solve the problem before attempting a solution. Likewise, the answer depends on the method of solution and experimental error. Instructors can use Physlets to ask questions indicative of those encountered in actual laboratory situations.

As another example, consider constant acceleration. Students have a great deal of difficulty not associating the direction of motion with the direction of acceleration (or force). The first script creates an animation showing a ball moving up with a constant downward acceleration while the second script creates a ball moving down with a constant downward acceleration. We ask students to determine the acceleration of these objects. Simply watching the motion of the ball and the time ought to allow the student to give an order of magnitude estimate of the answer.

Students must not only consider how to solve the problem, but also how to solve the problem with the least experimental uncertainty. In our experience, students who are well-versed in problem solving sometimes have little understanding of experimental error. When this type of problem was delivered on a homework assignment at NCSU, one insightful student remarked that the calculated acceleration was different depending on which equation of motion she used. The different results were a result of experimental error since the error in the measurement of the time at which the object stopped was greater than the error in the measurement of the position at which the object stopped. Hopefully this led the student to a greater understanding of experimental error. Unfortunately, some students believe that such exercises requiring observation, qualitative reasoning, and measurement should not be part of the lecture course, but left for the laboratory. Physlet problems are not, at present, given on tests or on the Medical Colleges Admission Test.

In introductory courses at Davidson College and NCSU, we are investigating the impact of multimedia-focused problems using Physlets on students’ problem solving skills and conceptual understanding. Students have greater difficulty solving these problems than similar traditional problems where necessary information is given in the text of the question. It is likely that students are accustomed to a "plug-and-chug" approach rather than qualitatively reasoning. However incorporating multimedia-focused problems using Physlets into daily instruction will likely help improve students’ impressions of these problems and help them learn the problem solving strategy required for solving them. Increased attention to qualitative reasoning may also have an impact on students’ conceptual understanding.

Our goal as curriculum designers and teachers is not to impress, but to meet the needs of learners. Through the development of multimedia-focused problems using Physlets, we believe we’ve found a powerful tool to challenge students’ conceptual understanding of physics as well as to change their approach to problem solving.


©1998 Wolfgang Christian and Computer in Physics, all rights reserved.