Chapter Twenty-One

Web Computing, Applets, Primitive Graphics

In this chapter we experience one of Java’s unique capabilities, namely, the ability to have its programs run over the World Wide Web (the “Web”). On account of Java’s Web prowess being a major force behind its popularity, it is important to learn something about applets, even if it is not enough to become a Web developer. Nevertheless, this chapter may be skipped without serious affect on the chapters to follow.

21.1 WHAT IS WEB COMPUTING?

Up to this point, we have been using Java to write much the same kind of programs you could write with conventional languages like Fortran and C. As indicated in Figure 21.1, we have put our source code in a file such as Applet1.java, and then compiled it with javac into byte code that is automatically placed in Applet1.class. We then executed Applet1.class with the java Applet1 command.

A unique aspect of Java is that you may create .class files to be executed via a Web browser on someone else’s computer attached to the World Wide Web. Browsers such as Netscape, Mozilla, Amiya, and Internet Explorer are programs that process files written in the Hypertext Markup Language (HTML). Hypertext refers to a document that, in addition to plain text, may also contain multimedia content (figures, data, movies, computer simulations, and sound). HTML is a language used to create hypertext documents. The “markup” aspect of the language refers to marks, analogous to those used by human typesetters to “mark up” a manuscript in preparation for typesetting, which indicate things like font type and spacings. As we shall see, the marks in HTML are tags like <em> enclosed in angle brackets.1

image

Figure 21.1 When running an applet, a compiled class file is executed from the command line or from a Web browser.

Listing 21.1 CallApplet.html, an HTML file (Web page) that starts off applet Applet1.

image

All HTML files end with the suffix .html (or sometimes .htm on Windows machines). Browsers read HTML files and both format the text it contains to look like a printed page, and display the referenced multimedia content appropriately. If the browser is modern, it should be equipped with a Java plug-in (an addition) that permits it to execute .class files. However, browsers cannot compile .java files (only developers, like you with SDK, are capable of doing that).

This is actually quite simple with applets. The Java programs that we have been writing so far are referred to as applications, in recognition of the fact that they apply computer science to something useful. Yet if you add two lines and modify one other, you will change an application program into an applet whose .class file runs via the Web via a browser. These files are called “applets,” since it is envisioned that they will be small applications that will not overload someone else’s computer when run over the Web. All applets run on the computer reading the Web page, and not on the server where the page is stored (that is a good thing because educational institutions are terribly underfunded and cannot afford to supply computer time to the whole world.)

An important thing about Java is that the language is written with a high degree of attention to security, which in this case means restricting which areas of memory a program may access. This is a good thing if you are to let someone else’s program (applet) run on your computer, and it is one example of how

image

Figure 21.2 A screen dump of the computer screen showing output from Applet1.

Java is designed for Web computing. For this reason, programs that read and write files will not work as applets, since they will not be permitted to write (and possibly damage) files on someone else’s computer. Likewise, we have seen that Java methods deal with arrays via reference calls in which the address of the array in memory is passed to the method. There are no commands in Java that permit you to manipulate these addresses or go to some other address in memory where you do not belong. This is in contrast to the use of pointers in a language like C, where you manipulate memory locations to do some very powerful programming—or do tremendous harm, even if that was not your intention.

The use of applets also protects you, the code provider. On the one hand, you are transmitting only your .class file to the Web computer, and so your source file cannot be damaged, or plagiarized, by the Web user. On the other hand, the .class file is running on their computer, not yours, and so regardless of how it fails, it cannot harm you.

21.2 IMPLEMENTATION: GET THIS TO WORK FIRST

If you are on a computer that has been set up to serve documents to the Web (a “Web server”), then the files you place in the directory or folder public html are viewable by anyone on the Web. It follows that if the .class file from your applet program is in public html, and if this class file is called by some .html file, then anyone’s browser is used to run your applet on their computer, wherever and whatever their computer may be.

To see how this all works (and make more sense of all these words), examine CallApplet.html in Listing 21.1. It is the HTML that calls the applet after being read by a browser, and produces an image on your screen like Figure 21.2. The executeable applet is the compiled version of Applet1.java in Listing 21.2.

1.  Save a copy of CallApplet.html in your public html directory/folder. If you do not have such a directory, then create one. You can copy CallApplet.html from the CD, from the Web, or from Listing 21.1.

Listing 21.2 Applet1.java

image

2.  Point your browser to the Web page CallApplet.html. When opened, this file prints out some lines on the browser’s screen and runs the program in the file Applet1.class. It knows to run the code via the statement on line 8:

image

This command tells the browser to load and run Applet1.class and to place the output of the program (a pretty graph) within a window in your browser of size width = 350 pixels × maxY = 250 pixels. A pixel stands for “picture element,” namely, a single dot on your screen. A typical screen may have an area of 1024 × 768 pixels, so a 350 × 250 graph should appear as a box of about 1/10 the screen size.

3.  Normally your browser will run the applet and print out line 6 someplace on your browser’s screen (but not if you call the HTML file with the soon-to-be- discussed appletviewer command).

4.  If you modify an applet that you are developing and want your browser to reload it, you need to depress the shift + reload keys simultaneously. Conversely, if you want to stop the applet from running, then pushing the back arrow on the browser seems safest. (Closing the browser window may still leave the applet running.)

5.  appletviewer: The SDK developer’s kit provides a shell command that activates an applet without a browser:

The applet does not look quite the same within appletviewer as it does with a browser, but this is a convenient and fast way to develop applets.

6.  Examine the graph drawn by your applet. Not bad for something we have done from scratch? One of the amazing things about Java is that this class file produces an identical graph on every Java-enabled computer system.

a.  Use the View/Page Source button on your browser to see the source HTML file that the browser is rendering on the screen for you. Look at line 8 calling the Java program Applet1.class.

b.  Instruct your browser to save this Web page in the appropriate directory for this chapter (File/Save As ... button on your browser). The file should have the name CallApplet.html. It should be similar to the file in Listing 21.1.

7.  Point your browser to Applet1.java and open it (the file is on the CD). Study Applet1.java. This is the Java source code, given in Listing 21.2, for an applet to draw a graph. Your browser will be able to read this file as text, list it on your screen, but not compile or execute it. Examine how the variable g represents a Graphics object that ultimately becomes the graph on your screen. The paint method draws the graph, and the world2win method determines the parameters needed to scale the graph so that it fits in the window on your computer screen. You will modify the paint method as part of your exercise.

8.  Tell your browser to save Applet1.java in the appropriate directory for this week’s work. (Doing that with the File>Save As commands is safer than cut and paste.)

9.  Applet1.class:This is a compiled byte code to be called by your browser as it reads CallApplet.html. Feel free to look at it, but it will not tell you much, as it is not meant to be read by humans.

10.  Create your own personal copy of Applet1.class by compiling Applet1.java.

11.  Open your copy of CallApplet.html with your browser (File > Open Page > Browse). If you did all the copying and compiling correctly, this should plot the graph again.

12.  Try out the alternate method for executing applets, issuing appletviewer from a shell:

image

13.  Try using the command java Applet1 to execute Applet1.class.

21.2.1 Understanding Applet1.java

Look inside Applet1.java to see what makes it go. On lines 2 and 3 we find:

image

These import commands tells the Java compiler to include packages of class files that extend Java beyond the basic classes. The java.applet package contains the class Applet that is needed to create applets. Consequently, when on line 4 we have the statement:

image

the word “extends” means that Applet1 inherits all the general properties of an Applet, as defined in java.applet. These include an applet’s ability to be displayed in a window, its ability to respond to events like the click of a mouse, and its being killed when no longer needed. Line 4 is how we declare our Applet1 to be an Applet. The compiler understands what an Applet is after the importation of line 2.

What is new in this program, aside from it being an applet, is that it draws graphical objects on your computer screen. Regardless of our graphics not being as fancy as what is possible with Java, the mere fact that we are able to write graphic commands that will run on most every computer is a major advance towards system-independent computing. The Abstract Windows Toolkit java.awt contains the classes for creating graphical objects such as lines, strings, rectangles, and ovals.2

Other than lines 2–4, the rest of the program has the same structure as the applications you have been writing up until now. However, they start their lives differently. As a consequence of applets beginning their execution from a Web browser, which is inherently a graphical interface, the applet must be “painted” onto a browser’s Web page. Thus, an applet’s execution begins in a method named paint, in contrast to the main method where execution begins for an application. If we had written an application, line 8 might declare our main method. Instead, execution of the applet begins with the call to the paint method:

image

You are free to put whatever you want in the paint method, but you must call it paint and it must have a graphical object as its argument. It is through this graphics context, g in our case, that the browser and applet communicate.

21.2.1.1 Transformation of Coordinates

We want to plot

image

Because f(0) = 0 and f(1) ~ 0.7, we need to plot ordinates in the range 0 < y < 1. These ranges for x and y are called actual or world values or coordinates. The plotting in our applet is done with basic Java graphics that deal with the display screen’s pixels. A typical screen, indicated on the left of Figure 21.3, may be 1,024 pixels wide and 768 pixels high. To draw our graph we need to convert the x and y values from (21.1) into pixel counts or window coordinates that fit on the screen. We assume a linear mapping between the two,

image

where the m’s and b’s are constants that we need to determine. The method world2sc solves for these constants and in the process as converts the values of x and y in doubles into ints needed for pixel values. To be safe, we leave a 10% margin around the graph.

image

Figure 21.3 Left: The coordinate system used to define the window (pixel) coordinates. The upper left corner corresponds to the point (0,0), the width of the window is 400 pixels, and the height is 350 pixels. The ywin coordinate increases downwards. Right: An image of the computer screen showing Applet2.

Rather than try to draw a smooth curve through 100 points (possible using splines [CP 05]), we draw 100 little straight lines connecting old points, (gOldX, gOldY) to new points (gNewX, gNewY) and hope that your eyes are not good enough to notice the steps. The for loop that generates the 100 line segments starts on line 18, and the actual drawing is done on line 23. Seeing that pixel coordinates are all integers, on lines 16–17 and 20–21 we use the cast operator (int) to convert or “cast” a double into an integer (recall, we must do this explicitly since Java will not let us reduce precision unless we insist).

21.3 EXPLORATION: MODIFY Applet1.java

1.  Copy the files CallApplet.html and Applet1.java into new files Applet2.html and Applet2.java respectively.

2.  Modify both these files so they will work as the applet Applet2.java. You will need to make the names of the Java source and class file consistent. This also means that you will have to compile Applet2.java to produce Applet2.class, since a direct renaming of Applet1.class will not work.

3.  Check that opening Applet2.html in your browser draws the graph again.

4.  Modify the program Applet2.java so that it also draws an x axis and a y axis with the graph. It should look like the right drawing in Figure 21.3.

a.  Hint 1: Draw a long line using the g.drawLine command on line 31, only now draw it from the origin to the edge of the box.

b.  Hint 2: It is easy to draw an axis outside of the piece of real estate you have reserved on the screen, and then not see the line at all (what a bummer). Accordingly, it is a good idea to make your program change progressively so that at first you draw the axes well within the reserved box and then see how close you can get the axes to the edges of the boxes before they disappear.

5.  Modify the source code to plot the function f(x) = tan(5x). To keep your curve within the boundary, like Figure 21.3, you may have to divide f(x) by 100.

6.  Make the straight-line nature of the drawing more evident by experimenting with the number of steps used in the program and observing the results. For example, try using 1/10 the number of steps, and 10 times the number of steps. Is there a limit to how smooth a graph you are able to create?

21.4 EXTENSION: PTPLOT AS APPLET*

Listing 21.3 PlotFourierSeries.java defines a class PlotFourierSeries derived from PlotApplet that configures and constructs a PtPlot.

image

21.5 EXTENSION: APPLET WITH BUTTON INPUT*

Listing 21.4 AppletWindow.java by Manuel Páez.

image

image

Now that we have learned how to do some elementary things with applets, it is time to examine to do some fancy things with them. Examine AppletWindow.java in Listing 21.4. It is a modification of our basic graph-plotting applet that takes user input for the minimum and maximum values of x and y to be plotted. Compile this source file and create AppletWindow.class.

The plotting part of this applet is the same as our previous one, yet it has some new features. On lines 6–7 we import some awt classes to handle events entered by depressing buttons. Next note on line 10 that we now have a button object defined for the Start button, and a string containing the word “start” to place on top of this button. Scrutinize next on line 11 how we declare two graphical TextField objects to contain the minimum and maximum values of x and y as read from the screen. On lines 21–28 we convert these graphical objects into strings, and then convert the strings into doubles. Other new operations are present in the init method on lines 72–92, and the actionPerformed method on lines 93–97. The init method adds the new buttons to the screen and sets up the links to transfer data into the program, while the actionPerformed method responds to the depression of the Start button and repaints the screen.

21.6 EXTENSION: AWT, JFC, AND SWING*

Sun Microsystems, the inventor and keeper of Java, has announced that the Abstract Windows Toolkit (awt) is being replaced by the Java Foundation Classes (JFC). JFC also contains the Swing classes javax.swing.* to replace the AWT scrollbars, buttons, textfields, and other graphics user interface components that are sensitive to bugs. As things go, AWT is still functional, the applet we have written should work for still some time. However, it is not recommended to mix Swing and AWT components, and to satisfy forward-looking readers, we now rewrite our AWT applet, Applet1.java as the swing-class applet JApplet1.java. Note the new components:

1.  The Swing component set contains containers, that is, windows that contain groups of controls or other containers. In the Swing hierarchy, the top-level containers provide places for containers of lesser hierarchy. Some of the top-level containers are JApplet, JPanel, and JDialog.

2.  Components are added to containers of lower hierarchy. One such level of hierarchy is contentPane, an internal component of each top-level container into which all visible components are placed.

3.  The JPanel class directs the distribution of atomic components in the drawing area. JPanel, as well as the other top-level containers, has a content pane into which the Swing components are added.

4.  A Swing application usually contains two top-level containers, such as frame (JFrame) or applet (JApplet), and panel, as well as atomic components like buttons, combo boxes, sliders, and text fields. A JApplet is a class that allows applets to use Swing features.

5.  An individual Swing component may contain one JFrame and several JPanes. The JFrame provides the window for the application.

21.6.1 Building a JApplet*

Listing 21.5 gives JApplet1, which has the same functionality as our previous graphing applet, only now with the Swing set. (An additional example is provided in Chapter 18, “Advanced Objects; Baton Projectiles.”) We recommend that the interested reader look at listing 21.5 for further JApplet experience.

Listing 21.5 JApplet1.java by Manuel Páez.

image

image

Given the preceding theory for JApplets, we now try to design one. We know we must have a class inherited from the JApplet, and another class inherited from the JPanel class. In addition, we shall draw our objects in the content pane of the object of JPanel. On line 4 we import awt in order to use the graphics() class, and on line 5 we import the Swing package to build a JApplet and a JPanel. Execution of the applet begins in the paintComponent(Graphics g) method on line 11, where the browser transmit the Graphics object g. This object is called the graphics context because it provides the context and methods for painting. To cite an instance, it contains information on the window size, the clipping region, the color, and the font, as well as the methods to draw a line, a rectangle, an oval, and so forth. Initialization is done in the init() method on line 45, which is called automatically.

The definition of the class Apj1 as derived from JApplet occurs on line 39. We see that Apj1 inherits all the properties and methods of JApplets. The statement on line 40 declares an instance of a new class derived from JPanel. The init() method on line 45 initializes the applet by declaring an instance of the class GraphPanel, which is defined as a class of the type JPanel with the JApplet class. This gets added to the content Pane of the JApplet. Finally, on line 56 the constructor of the GraphPanel class is defined, with the color white declared for the panel background. The remainder of the JApplet contains much the same code as Applet1.java.

21.7 EXAMPLE: BATON APPLET, JPARABOLA.JAVA*

In Figure 18.3 we show the output of the applet Jparabola.java written by Manuel Pàez (and found on the disk). This applet implements the OOP and physics ideas we have been discussing, and is available on the CD. We encourage all readers to try out the applet, even if they do not look inside to see what makes it work. In this section we describe what makes it work.

image

Figure 21.4 Flowchart of the applet JParabola.

As indicated by the flowchart in Figure 21.4, Jparabola starts by importing the necessary classes. It then sets the layout for the applet and then calls the method paintComponent to analyze the events needed to start the applet’s thread (pressing the buttons dumbell/bar followed by start). Events changing the initial velocity are originated by the slider bars. If the stop button is pressed, the thread stops and the program waits for further events.

When the applet is loaded by a browser, the browser (or appletviewer) transfers to it a graphics context in which to plot elements. The applet is initialized with the init() method and continues with the paintComponent method that sets watchers to the action of the buttons, sliders, and system actions. If the start button is pressed, a thread to start the motion is begun, and the motion continues until it is stopped or the projectile hits the ground.

Because the Applet uses the swing technology, it needs instances of JApplet andJPanel. From these it constructs three classes:

1.  JParabola: inherits properties of JApplet and contains other two classes.

2.  ParabolaPanel: inherits properties of JPanel and implements Runnable. Because a Thread is defined, the object ActionListener is implemented in order to listen for the buttons that generate actions.

3.  ListenToSlider: controls the action of the sliders and creates instance of ChangeLister.

As was needed for our most elementary applet, JParabola contains class variables used in transforming from world (x, y) to window (X, Y ) coordinates. In addition, JParabola contains class variables used in transforming time and energy to window (T, E). The init() method establishes the layout for the applet. It contains a main JPanel, ParabolaPanel, which uses a BorderLayout:

1.  North: a JSlider to select the initial angle of the projectile.

2.  West: another JSlider to select the initial velocity of the projectile.

3.  Center: on the left, the location of the graphs for the parabolic motion, on the right, the energy graphs.

4.  South: another JPanel formsPan using a BorderLayout with a button and JTextFields to set the dumbell’s masses and length. Also buttons to start or stop the motion, with similar button on the right for a solid bar.

ParabolaPanel: The class ParabolaPanel inherits properties of a JPanel, and contains methods:

1.  ParabolaPanel(): class constructor and variable initializer.

2.  world2sc(): transforms world to global coordinates.

3.  energycoor(): transforms world to global coordinates for E and t.

4.  xyaxis(): plots the x-y axis of right graph.

5.  initval(): uses JSliders to determine initial velocity of projectile.

6.  DrawDumbell(), DrawBar(): draws trajectory and plots energy.

7.  motion(): computes and plots (x, y), and calls method to add rotation.

8.  run(): in action until stop button pressed or motion ends. Freezes motion for several milliseconds so that user sees the positions of the dumbell and steps through the time used in motion method.

9.  setInitAngle, setInitVel: converts JSlider readings to doubles, draws initial velocity vector.

10.  beginMov(): called when “start” depressed, starts thread, sets time to 0.

11.  paintComponent(): the main program, the internal thread that continuously watches these programs.

12.  actionPerformed(): listens for events caused from buttons and reads JTextFieldsds.

The class class ListenToSlider implements ChangeListener and continuously detects the JSliders to see if they have moved. Its call to method beginMov starts the motion thread.

21.7.1 Exercises for JParabola

1.  Observe the motion of the dumbell for different masses and lengths, and how the heavier mass remains closer to the parabolic COM trajectory.

2.  Does the time in the air depend upon the mass?

3.  What properties of the baton’s motion change when the mass increases?

4.  Is the baton at rest at the highest point in its trajectory?

5.  Is the sum of the translational KE + PE constant?

6.  Is total energy constant?

7.  Is rotational energy constant?

21.8 KEY WORDS

applet

appletviewer

application

browser

byte code

HTML

hypertext

just-in-time compiler

markup language

pixels

WWW

21.9 SUPPLEMENTARY EXERCISES

1.  You are writing a Java program or applet designed to run over the World Wide Web. Explain in just a few words the purpose or content of each of the following:

a.  Program.java

b.  javac

c.  java

d.  Program.html

e.  Program.class

f.  appletviewer

2.  Explain in just a few words:

a.  what makes the main method different from all other methods;

b.  what is a Web browser;

c.  what is special about the paint method in an applet;

d.  on what computer does an applet run;

e.  on what computer is an applet compiled;

f.  how you get an applet to write out to a file.

1  We do not do much with HTML in this chapter. However, in Part 3 of this book we do study another markup language, image.

2  A useful reference on this subject is the free textbook by D. Eck [Eck 02]. Other books often examine older versions of Java, even if they call them Java2, Java3, or Java4. Eck uses JFC (Java Foundation Class) and swing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.127.197