Chapter 2
Java Applet and User Interface

2.1  Introduction

Up to now, our Java programs (e.g., GPoint and GVector) have been executed by creating Java classes (e.g., TestGPoint and TestGVector) that contains a main() method, which the interpreter looks for when asked to run a class. These Java programs are standalone Java applications that can be run by using only the Java interpreter, for example, from a command line. However, much of Java's current popularity has come about because of Java-capable World Wide Web browsers such as Netscape Navigator and Microsoft Internet Explorer. A Java-capable browser can download and play Java programs, called applets, on the user's system. An applet is nothing more or less than a Java class that inherits from the Java API Applet class and implements certain methods that need to be present for the applet to handle its appearance and to respond to events passed to the applet. Applets appear in a Web page much the same way as GIF and JPEG images do, but unlike images, applets are dynamic and interactive. Applets can be used to create forms, graphics, animation, and games that immediately respond to input from the user. In this chapter, you will learn about how applets, browsers, and the World Wide Web work together.

Java provides a package of classes called the Abstract Window Toolkit or Another Window Toolkit, which we shall simply refer to as the AWT. The AWT contains a Graphics class that allows you to draw lines, polygons, rectangles, ovals, and so on. One of the major tasks in this chapter is to show you how to use an graphics object to draw and fill some primitive geometric shapes. However, we will not cover all drawing and filling methods provided by Java since what we need to use in this book is very fundamental methods to draw a line and to fill a closed polygon. We shall show you that, with these fundamental tools, you can draw a sophisticated geometry and create impressive graphics of your own.

In the early 1980s we went to a computer show in our hometown in China. For the first time, we encountered a pointing device called ``mouse'' that is attached to an Apple Macintosh computer. After playing the computer with mouse for a while, we found it so useful that we convinced our company to buy Macintosh computers rather than other IBM compatible personal computers that had no mice yet. With the rise in popularity of graphical user interfaces in MS-DOS, UNIX, and OS/2, use of mice is growing throughout the personal computer and workstation worlds. For this reason, we shall show you how to use your mouse as an essential tool for interactive graphics design.

Another major task of this chapter is to show you how to create powerful user interface (UI for short) components such as buttons, labels, text fields, and scroll bars so that you can interact with applets through these elements. Using the AWT, a user interface consists of three things:

In this chapter, we shall not go though each of them in detail. The container we use in this book is usually the applet itself. The layout managers covered in this chapter are the FlowLayout and BorderLayout.

2.2  Hello applets

We start with showing you how to create a simple Java applet that, when loaded by a Java-capable browser, draws the string ``Hello, this is my first applet.'' on the applet's display area. Let's name the applet Hello1 and type the following code:

import java.awt.*;
import java.applet.Applet;

public class Hello1 extends Applet
{
   // Decalare and create an object f from Font class:
   Font f = new Font("TimesRoman", Font.BOLD, 28);

   // Implementation of the paint() method:
   public void paint(Graphics g)
   {
      // Set user defined font:
      g.setFont(f);

      // Set paint color to green:
      g.setColor(Color.green);

      // Draw string:
      g.drawString("Hello, this is my first applet.", 5, 40);
   }
}

As it is seen, we define a class called Hello1 that is a subclass of java.applet.Applet. Since we shall work on font, color, and graphics, these classes are imported from the AWT package. The most important thing you need to know about this applet is the paint() method. The paint() method is the place where the communication of this applet really occurs. The Graphics object passed into the paint() method holds the information of the drawing surface such as foreground and background colors or clipping area. In our implementation of paint() method, we change the default font to a user-defined font (i.e., ``TimesRoman" with 28 points) and the default color to green, then draw the string ``Hello, this is my first applet.'', starting at the position (5, 40). Note that the origin for (x, y) is at the top left of the applet's drawing area with positive y moving downward.

Save the above code under the name Hello1.java in C:\JBook\Ch2 and type

C:\JBook\Ch2>javac Hello1.java
to compile the applet. As it was said previously, an applet is loaded and run by a Java-capable browser. Therefore, you need to create a Web page that will hold the applet by using the HTML language (more specifically, the HyperText Markup Language). If you are new to the HTML language, do not worry since what we need is a very simple HTML file of the following form:
<HTML>
<TITLE>HelloApplet</TITLE>
<BODY>
<CENTER><APPLET CODE="Hello1.class", WIDTH=350 HEIGHT=60></APPLET></CENTER>
</BODY>
</HTML>

In the above list, HTML, TITLE, BODY, etc. are called HTML tags which consist of a left angle bracket ( < ), a tag name, and a right angle bracket ( > ). Tags are usually paired (e.g., < TITLE > and < /TITLE > ) to start and end the tag instruction. The end tag looks just like the start tag except a slash (/) precedes the text within the brackets. An applet is included in the HTML Web page by using a special tag APPLET. A Java-capable browser use the information contained in the tag to locate the compiled applet (the Hello1.class in our example) and run the applet itself. To see how it works, you save the code under the name Hello1.html in the same directory as Hello1.class locates. Then, use your Java-capable browser to open it. To see how the applet should look like, please click Hello1.

With Java applications, you can pass parameters to your main() method by using on line arguments stored in args[]. In what follows, we shall show you how to pass parameters from HTML Web page to your applet. First, we copy the Hello1.java and Hello1.html files to Hello2.java and Hello2.html files. We then modify the Hello2.html as follows:

<HTML>
<TITLE>HelloApplet</TITLE>
<BODY>
<CENTER>
<APPLET CODE="Hello2.class", WIDTH=350 HEIGHT=60>
<PARAM NAME=font VALUE="Courier">
<PARAM NAME=size VALUE="18">
</APPLET>
</CENTER>
</BODY>
</HTML>

As it is seen, we indicate each parameter by using the tag PARAM, which has two attributes for the name and value of the parameter. It should be noted that the value is given as a string.

We now modify Hello2.java so that it can take parameters from Hello2.html Web page.

import java.awt.*;
import java.applet.Applet;

public class Hello2 extends Applet
{
   // Decalaration:
   Font  f;

   public void init()
   {
      String fontName, str;
      int    fontSize;

      // Fetch the font parameter from Web page:
      fontName = getParameter("font");
      if (fontName == null)
         fontName = "NewRoman";

      // Fetch the font size from Web page:
      str = getParameter("size");
      if (str == null)
      {
         fontSize = 12;
      }
      else
      {
         // Convert the string to integer:
         fontSize = Integer.parseInt(str);
      }
      // Create an object from Font class:
      f = new Font(fontName, Font.BOLD, fontSize);
   }

   // Implementation of the paint() method:
   public void paint(Graphics g)
   {
      // Set user defined font:
      g.setFont(f);

      // Set paint color:
      g.setColor(Color.green);

      // Draw string:
      g.drawString("Hello, this is my first applet.", 5, 40);
   }
}

In the above code, we added an important method init() to the Hello2 class (More accurately, we overridden the default implementation of init() method). The init() method takes care of any necessary initialization for the applet. In our case, the init() fetches parameters from the Web page for font name and size. You may now compile Hello2.java and run it by opening the Hello2.html file with your browser. To see how the applet should look like, please click Hello2.

2.3  Drawing and filling

Most of the graphics capabilities in Java are methods defined in Graphics class. With these tools you can draw lines, rectangles, arcs, ovals, and polygons. You can also perform flood filling in a closed shape such as a rectangle, an oval, or a closed polygon. In this section, we shall show you how to do so.

We start with reviewing the coordinate system of an applet's drawing area. By default, the origin (0,0) of the coordinate system is at the top left corner of the applet's drawing area. Positive x values are to the right and positive y value are downward. Units are measured in pixel values. Therefore, the x- and y-coordinate are integers. Such coordinate system arrangement agrees with a coordinate system of your computer screen, although it is different from that of analytic geometry.

We now create the applet MyDraw that draws a line, a rectangle, an oval, and an arc in the applet's drawing area. The source code of MyDraw is listed below.

import java.awt.Graphics;
import java.applet.Applet;

public class MyDraw extends Applet
{
   public void paint(Graphics g)
   {
      // Draw a line from (0, 0) to (60, 40).
      g.drawLine(0, 0, 60, 40);

      // Draw a rectangle that starts at (150,20) and extends
      // 120 and 80 units in positive x and y directions.
      g.drawRect(150, 20, 120, 80);

      // Draw an a circle in an square that starts at (20,100) and
      // extends 100 units in both x and y positive directions.
      g.drawOval(20, 100, 100, 100);

      // Draw an arc. The first four values are used to define a 
      // rectangle and the last two values define the starting and
      // swept angle in counter-clockwise orientation. If the last
      // value (i.e., the swept angle) is negative, the orientation
      // is then clockwise.
      g.drawArc(180, 120, 80, 80, 180, 180);
   }
}

The comments in the code have explained the usage of each drawing method. Save the code under the name MyDarw.java in C:\JBook\Ch2 and compile it to get MyDraw.class. To see how it works, we create the following HTML file with the name MyDraw.html:

<HTML>
<TITLE>MyDraw Applet</TITLE>
<BODY>
<CENTER>
<APPLET CODE="MyDraw.class", WIDTH=350 HEIGHT=250></APPLET>
</CENTER>
</BODY>
</HTML>

To see how the applet should look like, please click MyDraw.

To demonstrate flood fill capability, we copy MyDraw.java to MyFill.java and modify it as follows:

import java.awt.*;
import java.applet.Applet;

public class MyFill extends Applet
{
   public void paint(Graphics g)
   {
      g.setColor(Color.red);
      g.fillRect(150, 20, 120, 80);

      g.setColor(Color.green);
      g.fillOval(20, 100, 100, 100);

      g.setColor(Color.blue);
      g.fillArc(180, 120, 80, 80, 180, 180);
   }
}

To invoke the MyFill applet, we create and then open the following HTML file under the name MyFill.html:

<HTML>
<TITLE>MyFill Applet</TITLE>
<BODY>
<CENTER>
<APPLET CODE="MyFill.class", WIDTH=350 HEIGHT=250></APPLET>
</CENTER>
</BODY>
</HTML>

To see how the applet should look like, please click MyFill.

Since the HTML files used in this book are similar and very simple, we shall no longer list the source code. You can either create them yourself or copy them to your working directory from the companion disk. By default, we name the HTML file by the same name as the applet to be invoked and save it in the same directory where the applet resides.

2.4  Mouse events

An event is generated in response to just any thing that occurs during the life cycle of your applet. The following are the events that you may deal with in your programs:

  • Mouse clicks: mouse button pressed, mouse button released, or mouse button clicked.
  • Mouse movements: mouse moved or mouse dragged.
  • Key-presses: key pressed, key released, and key typed.
  • User interface events: buttons clicked, scroll bars scrolled up and down, text string in a text field changed, etc.
  • Window events: window opened, window closed, and window resized.

When an event is generated, it is handled through an event listener, which represents a set of events, that has been registered. In this book, we will not cover all the events listed above. Instead, we will focus on mouse events in this section and user interface events in the next section.

Different listeners are defined by different interfaces contained in the java.awt.event package. If you look at the API documentation or the source of these interfaces, you will be able to figure out which listener interfaces go with which events and also the methods in those interfaces. Table 2.1 shows the events and methods that two mouse listener interfaces contain:

Listeners Events Methods
MouseListener mouse button down public void mousePressed(MouseEvent e)
mouse button up public void mouseReleased(MouseEvent e)
mouse button clicks public void mouseClicked (MouseEvent e)
mouse enter public void mouseEntered(MouseEvent e)
mouse exit public void mouseExited(MouseEvent e)
MouseMotionListener mouse move public void mouseMoved(MouseEvent e)
mouse drag public void mouseDragged(MouseEvent e)

Table 2.1: Listener interfaces and their methods

The methods in Table 2.1 are defined in the MouseListener and MouseMotionListener interfaces and implemented as stubs in the MouseAdapter class. When implementing an interface, you have to include all stubs in your code and add actual code to the methods you are interested in.

We now walk through three examples to get a good grasp of implementation. Our first example is to create an applet Click so that a circle is drawn at the cursor position while you move and click your mouse. The source code of this applet is given below:

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class Click extends Applet implements MouseListener
{
   int orx, ory;

   public void init()
   {
      orx = 20;
      ory = 20;
      addMouseListener(this); // Register event listener
   }

   // Required to declare listener interfaces:
   public void mousePressed(MouseEvent evt){}
   public void mouseReleased(MouseEvent evt){}
   public void mouseEntered(MouseEvent evt){}
   public void mouseExited(MouseEvent evt){}

   // Set center to mouse position:
   public void mouseClicked(MouseEvent evt)
   {
      orx = evt.getX();
      ory = evt.getY();
      repaint();
   }

   public void paint(Graphics g)
   {
      g.drawOval(orx-20, ory-20, 40, 40);
   }
}

The keyword implements indicates that you will implement the interface by hand since the MouseListener does not have an adapter class. Referring to Table 2.1, the MouseListener has five stub methods of which only the mouseClicked() method is of interest. Therefore, we implement only the mouseClicked() method that is invoked whenever the user clicks the mouse button. In the mouseClicked() method, we update the center of oval (i.e., xor and yor) by the current mouse position. To see how the applet works, please click Click.

Our second example is to create an applet so that you can drag a circle to anywhere you want. The applet is called Drag and is implemented as follows:

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class Drag extends Applet implements MouseMotionListener
{
   int orx, ory;

   public void init()
   {
      orx = 20;
      ory = 20;
      addMouseMotionListener(this); // Register event listener
   }

   // Required to declare listener interfaces:
   public void mouseMoved(MouseEvent evt){}

   // Implement the mouseDragged method():
   public void mouseDragged(MouseEvent evt)
   {
      orx = evt.getX();
      ory = evt.getY();
      repaint();
   }

   public void paint(Graphics g)
   {
      g.drawOval(orx-20, ory-20, 40, 40);
   }
}

The interface method we implemented in the applet is the mouseDragged() method in which the center of the oval is updated by the current mouse position. To see how the applet works, please click Drag.

Our final example is to create an applet that lets you draw a single line by pointing to where the line is to begin, pressing and holding down the left mouse button, and then dragging the mouse to the desired end point. When the button is released, the line is frozen. However, while the button is pressed, the applet continues to draw the line from initial location of the mouse, where the button was pressed, to the mouses current position. Therefore, as the mouse is moved around the screen, the line will shrink and stretch as needed. This type of line is called a rubber-banding line because it appears to be flexible like a rubber-band. We call our applet the RubberBand and implement it as follows.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class RubberBand extends Applet 
implements MouseListener,MouseMotionListener
{
   Point startPoint=new Point();
   Point endPoint=new Point();

   public void init()
   {
      // Register event listeners:
      addMouseListener(this);
      addMouseMotionListener(this);
   }

   // Required to declare listener interfaces:
   public void mouseClicked(MouseEvent evt){}
   public void mouseEntered(MouseEvent evt){}
   public void mouseExited(MouseEvent evt){}
   public void mouseMoved(MouseEvent evt){}

   // Set start-point to mouse position when mouse is down:
   public void mousePressed(MouseEvent evt)
   {
      startPoint.x = evt.getX();
      startPoint.y = evt.getY();
   }

   // Set end-point to mouse position when mouse is up:
   public void mouseReleased(MouseEvent evt)
   {
      endPoint.x = evt.getX();
      endPoint.y = evt.getY();
      repaint();
   }

   // Dynamically update end-point to mouse position:
   public void mouseDragged(MouseEvent evt)
   {
      endPoint.x = evt.getX();
      endPoint.y = evt.getY();
      repaint();
   }

   public void paint(Graphics g)
   {
      g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
   }
}

Since this example uses both the MouseListener and MouseMotionListener interfaces, we have to include all the definitions of stubs for these two listeners and add actual code to two interested methods: mousePressed()and mouseDragged(). When you press down any mouse button, the mousePressed() method sets the starting point of a line to the mouse position. If you hold down the mouse button and move the mouse, the mouseDragged() method updates dynamically the end point of the line to the current mouse position. Visually, you will see a rubber-banding line on the applet's drawing area. Please click RubberBand to the how the applet works.

2.5  User interface components

In this section, we will take a look at how to construct user interfaces (UI) within Java applets. Java's AWT (Abstract Window Tool) organizes on-screen elements into components and containers. A component is any on-screen object such as labels, buttons, text fields, etc. A container is a type of component that can contain other components or containers.

One of the neat things about an applet is that because it is already an AWT container, you can start adding other AWT components to them right away without having to understand a lot about the complicated parts of the AWT. For this reason, you will find it fairly easy to add labels, buttons, check boxes, choice menus, and text fields to your applets. Let us start now.

The first thing you will learn is to add three buttons ``Red'', ``Green'' and ``Blue'' to an applet Buttons such that, when one of the buttons is clicked, a rectangle in your drawing area will be filled with the color of your choice. The source code of Buttons applet is listed as follows:

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class Buttons extends Applet
{
   // Define default color as white:
   Color myColor = new Color(255, 255 ,255);

   public void init()
   {
      setLayout(new FlowLayout());
      Button button;
      button = new Button("Red"); // Create a button with label "Red"
      add(button);  // Add the button to your applet

      button = new Button("Green");
      add(button);

      button = new Button("Blue");
      add(button);
      setBackground(Color.lightGray);
   }

   public void paint(Graphics g)
   {
      // Fill rectangle with chosen color:
      g.setColor(myColor);
      g.fillRect(80, 80, 120, 80);
   }
}

The above Buttons class has two methods init() and paint(). As we mentioned in the introduction section, the arrangement of components in an applet is done by the layout manager. The call to setLayout() method in this example is to invoke the FlowLayout() manager witch is also the default layout manager. There are three alignment setting arguments you may choose, namely FlowLayout.LEFT, FlowLayout.CENTER, and FlowLayout.RIGHT with FlowLayout.CENTER being the default setting. In our code, we did not use any alignment input argument so that three components will be arranged with center-justification alignment. The init() method also creates three buttons and add them to the container which, in our case, is the Buttons applet itself. The paint() method performs flood filling with the color defined in mycolor object.

If you compile and run this applet, you will be able to see three buttons added to your applet. However, nothing happens when you click one of the buttons since no method has been implemented to handle button clicking event. In Java 2.1 and above, the events you can handle for the basic UI components are the same. Each event class has a corresponding listener interface with a set of methods to implement. We modify the Buttons applet to include an ActionListener interface and an event handling method as follows.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class Buttons extends Applet implements ActionListener
{
   // Define default color as white:
   Color myColor = new Color(255, 255 ,255);

   public void init()
   {
      setLayout(new FlowLayout());
      Button button;
      button = new Button("Red");  // Create a button with label "Red"
      button.addActionListener(this); // Register the listener:
      add(button);   // Add the button to your applet

      button = new Button("Green");
      button.addActionListener(this);
      add(button);

      button = new Button("Blue");
      button.addActionListener(this);
      add(button);
      setBackground(Color.lightGray);
   }

   public void actionPerformed(ActionEvent evt)
   {
      String buttonName = evt.getActionCommand();
      if (buttonName.equals("Red"))
         myColor = new Color(255, 0, 0);
      else if (buttonName.equals("Green"))
         myColor = new Color(0, 255, 0);
      else if (buttonName.equals("Blue"))
         myColor = new Color(0, 0, 255);
      repaint();
   }

   public void paint(Graphics g)
   {
      // Fill rectangle with chosen color:
      g.setColor(myColor);
      g.fillRect(80, 80, 120, 80);
   }
}

The keyword implements indicates that you will implement the interface by hand since the ActionListener does not have an adapter class. The interface method actionPerformed() is invoked whenever the user clicks one of the button. In the actionPerformed() method, the getActionCommand() extracts the label of the clicked button. Depending on the label is ``Red'', ``Green'', or ``Blue'', the color object mycolor is set to the corresponding color. If you compile and run this applet, you will be able to set different filling color by clicking respective button. To try this applet, please click Buttons.

We now consider labels and text fields. A label is an non-editable text string that acts as a description for other AWT components. On the other hand, a text field provides an editable area where you can either enter or output your text string. We shall implement the TextFields applet that allows you to type a text in a text field and outputs what you typed in the drawing area when you hit the return key. The source code of TextFields applet is listed below.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class TextFields extends Applet implements ActionListener
{
   TextField f;
   String str;
   boolean typed;

   public void init()
   {
      typed = false;
      setLayout(new FlowLayout(FlowLayout.LEFT));
      add(new Label("You type:"));
      f = new TextField(40);
      f.addActionListener(this);
      add(f);
   }

   public void actionPerformed(ActionEvent evt)
   {
      str = f.getText();
      typed = true;
      repaint();
   }

   public void paint(Graphics g)
   {
      if (typed)
         g.drawString("What you typed is: "+str, 5, 50);
      typed = false;
   }
}

When you hit the return key, the actionPerformed() method is invoked. The first statement in actionPerformed() sets the variable typed to true and the second statement calls the repaint() method, which in turns calls the paint() method. Accordingly, the paint() method draws a string you typed in the text field in the applet's drawing area. Again, we use FlowLayout manager to arrange the text field component with left-justification alignment. To see how the applet should look like, please click TextFields.

The last UI component we shall create is the scroll bars. A scroll bar is a visual tool used to select a value between a minimum and a maximum value. With the scroll bar, you can change the value by one of the following methods:

  1. Arrow on either end, which increment of decrement the value by 1 (the default unit).
  2. A range in the middle, which increments or decrements the value by a prescribed amount (10 by default).
  3. An elevator (or thumb) whose position indicates the current value. Moving this elevator with mouse causes continuous change in value.

Let's call the last applet example the MyScrollBars that fills a rectangle in red color. The width and height of the rectangle are determined by using the horizontal and vertical scroll bar respectively. The source code of MyScrollBars is listed below:

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class MyScrollBar extends Applet
implements AdjustmentListener
{
   int       width, height;
   Scrollbar hbar, vbar;

   public void init()
   {
      setLayout(new BorderLayout());
      width = 200;
      height = 150;

      // Design horizontal scroll bar:
      hbar = new Scrollbar(Scrollbar.HORIZONTAL, width, 10, 0, 370);
      hbar.addAdjustmentListener(this);
      add("South", hbar);

      // Design vertical scroll bar:
      vbar = new Scrollbar(Scrollbar.VERTICAL, height, 10, 0, 270);
      vbar.addAdjustmentListener(this);
      add("West", vbar);
   }

   // Get the current value from scroll bar:
   public void adjustmentValueChanged(AdjustmentEvent evt)
   {
      width = hbar.getValue();
      height = vbar.getValue();
      repaint();
   }

   public void paint(Graphics g)
   {
      // Fiil rectangle in red:
      g.setColor(Color.red);
      g.fillRect(20, 20, width, height);
   }
}

As it is seen in the init() method, this time we use BorderLayout manager that arrange UI components in four directions, namely the ``North'', ``East'', ``South'', and ``West''. In our case, we add the horizontal scroll bar to the ``South'' and vertical scroll bar to the ``West'' of the applet. It is also noted that the elevator of the horizontal scroll bar is initialized at the current width value. The minimum and maximum values of the horizontal scroll bar are respectively 0 and 380. The increment (or decrement) amount for clicking the range in the middle is set to 10. The design of the vertical scroll bar is similar and hence left for you to figure out. The adjustmentValueChanged() method is implemented to update either the width or the height when you select new values from the scroll bars. Save this code under the name MyScrollBar.java in Ch2 directory and compile it to get MyScrollBar.class. Then, write a HTML file to invoke the applet. Please click MyScrollBar to see how the applet works.

2.6  Putting it together

In this section, we shall demonstrate a practical application of the techniques learned in this chapter: computing the centroid (i.e., the center of mass) and area for a lamina - a thin sheet material. Let D be a region consisting the boundary of the lamina and its interior. Then, the area of the lamina is given by
A =



D 
dxdy.
Let r denote the density of mass of the lamina. In most engineering applications, the density r is a constant. In this case, the mass of the lamina is given by
M =



D 
rdxdy = rA.
The moments of the lamina about the x- and y-axis are
Mx = r



D 
y dxdy,    My = r



D 
x dxdy.
Denoting
_
M
 

x 
=



D 
y dxdy,    _
M
 

y 
=



D 
x dxdy,
the centroid is given by
xc = Mx
M
=
_
M
 

x 

A
,    yc = My
M
=
_
M
 

y 

A
.
If the boundary of the lamina is defined by a closed polygon which has n vertices (xi, yi), then the formulas to compute area and centroid can be simplified as

       A = -1/2i = 1n-1(yi+yi+1)(xi+1-xi),

       [`M]x = -1/6i = 1n-1(xi+1-xi)(yi2+yiyi+1+yi+12),

       [`M]x = 1/6i = 1n-1(yi+1-yi)(xi2+xixi+1+xi+12).

We now discuss implementation details. Let's call the applet Lamina and consider what the applet should have to perform the task. Firstly, we need to provide users with a capability to draw a polygon on the drawing area of an applet. This is better implemented in the mouseDrag() method. Secondly, we need to add two buttons for users to perform either the computation of the centroid and area or redrawing an lamina. Thirdly, we need to have two text fields to output computation results. The source code of the Lamina applet is listed below.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class Lamina extends Applet
implements ActionListener, MouseMotionListener
{
   final int  max_num_points = 1000;
   int        xval[]=new int [max_num_points];
   int        yval[]=new int [max_num_points];
   int        npts;
   TextField  fieldCenter, fieldArea;
   boolean    compute;

   public void init()
   {
      setLayout(new FlowLayout(FlowLayout.LEFT));
      Button b = new Button("Redraw");
      b.addActionListener(this);
      add(b);
      b = new Button("Compute");
      b.addActionListener(this);
      add(b);

      add(new Label("Area="));
      add(fieldArea = new TextField(8));
      add(new Label("Center="));
      add(fieldCenter = new TextField(10));

      // Register mouse listener:
      addMouseMotionListener(this);

      npts = 0;
      compute = false;
      setBackground(Color.lightGray);
   }

   public void actionPerformed(ActionEvent evt)
   {
      String buttonName = evt.getActionCommand();
      if (buttonName.equals("Compute"))
         compute = true;
      else
      {
         compute = false;
         npts = 0;
      }
      repaint();
   }

   // Required to declare listener interfaces:
   public void mouseMoved(MouseEvent evt){}
   
   // Save mouse position when it is dragged:
   public void mouseDragged(MouseEvent evt)
   {
      if (npts < max_num_points && compute == false)
      {
         xval[npts] = evt.getX();
         yval[npts] = evt.getY();
         npts++;
         repaint();
      }
   }

   public void paint(Graphics g)
   {
      int cent[] = new int[2];
      int area[] = new int[1];

      if (compute == false)
      {
         // Redraw the text fields:
         fieldCenter.setText(String.valueOf(""));
         fieldArea.setText(String.valueOf(""));

         // Draw the polygon in black color:
         g.setColor(Color.blue);
         for (int i=1; i<npts; i++)
            g.drawLine(xval[i-1], yval[i-1], xval[i], yval[i]);
      }
      else
      {
         // Force the polygon to be closed:
         xval[npts] = xval[0];
         yval[npts] = yval[0];
         npts++;

         // Fill polygon region with green color:
         g.setColor(Color.green);
         g.fillPolygon(xval, yval, npts);

         // Compute area and centroid:
         CompAreaCenter(npts, xval, yval, area, cent);

         // Draw a red circle at the centroid:
         g.setColor(Color.red);
         g.fillOval(cent[0]-2, cent[1]-2, 4, 4);

         // Write results in the text fields:
         fieldArea.setText(String.valueOf(area[0]));
         String str = String.valueOf(cent[0])+", "+String.valueOf(cent[1]);
         fieldCenter.setText(String.valueOf(str));
      }
   }

   private void CompAreaCenter(int npts, int xval[], int yval[], int area[], int cent[])
   {
      int  i;
      int  x1, x2, y1, y2, m_x, m_y;

      area[0] = m_x = m_y = 0;
      for (i=0; i<npts-1; i++)
      {
         x1 = xval[i];
         x2 = xval[i+1];
         y1 = yval[i];
         y2 = yval[i+1];
         area[0] -= (y1 + y2) * (x2 - x1);
         m_x -= (x2 - x1) * (y1 * y1 + y1 * y2 + y2 * y2);
         m_y += (y2 - y1) * (x1 * x1 + x1 * x2 + x2 * x2);
      }
      area[0] /= 2;
      m_x /= 6;
      m_y /= 6;
      if (area[0] != 0)
      {
         cent[0] = m_y / area[0];
         cent[1] = m_x / area[0];
         area[0] = Math.abs(area[0]);
      }
   }
}

Save the above code under the name Lamina.java in Ch2 directory and compile it to get Lamina.class. Then, we write a HTML file named Lamina.html to invoke the Lamina applet. To see how the applet works, please click Lamina.

2.7  Summary and references

In the first chapter, we introduced you the essential Java syntax and object-oriented programming concepts. All Java programs covered in that chapter are so called standalone Java applications and run by using only the Java interpreter, for example, from a command line. In this chapter, we introduced you the concepts of Java applets and the techniques of creating and invoking Java applets with HTML files by Java-capable browsers such as Netscape Navigator and Microsoft Internet Explorer. To meet the needs of interactive graphics design in subsequent chapters, we showed you a number of examples that allow you to communicate with the applets by using a mouse and UI (User Interface) components. Since a mouse is an essential communication tool between the user and computer system, we covered most of mouse-related methods such as mousePressed(), mouseReleased(), mouseClicked(), mouseDragged(), and mouseMoved(). In contrast, we discussed only a limited number of UI components and a few simple ways to organize the components for the following reasons:

  • UI components and theirs design are largely dependent on the programming language and its environment. For example, if you use the Microsoft Visual Basic or Visual C++ as your programming tool, you will find the design of UI components are very different. In Visual Basic and Visual C++, you drag desired UI components from the tool box and place them in your drawing area, which is known as the process of visual design. Then, you add actual code in the method corresponding to the specific UI component. To avoid deeply involving in a particular language and its environment, we on purpose use only limited number of UI components that are conceptually straightforward and easy to implement.
  • The design and management of UI components could be very simple or complex. In our case, we want to keep thing simple for you to learn. When you have mastered the essential skills, you can then redesign the applets presented in this book to make them reflect your preference. For example, you may use nested containers and panels, which are components themselves, to hold and organize your UI components (e.g., buttons, labels, text fields, etc.) and use canvas for drawing.
  • If you have been around computers for a while, you must have noted that software venders are continuously upgrading and modifying their products. When the new versions of their products are in the market, many computer books written specifically for previous versions are then quick out of date. For example, if you happen to have some Java programming books written before Java 2.1, you will note that quite a few methods for handling mouse and UI events are no longer recommended. If you continue to use such methods you will get compiling warnings that may look like ``uses or overrides a deprecated API'', which means that you are using the methods that may not be supported in the future. At the time of this writing, the latest Java version is 2.2 in which the Java Foundation Classes(or JFC for short) Swing is used to encompass a group of features to help users build graphical user interfaces. One of the features in JFC is the Swing that include everything from buttons to split panes to tables. Rather than taking the risk of introducing you some things that may be quickly out of date, we have cautiously chosen the simple UI components and layout so that they can be easily modified when it is necessary.

For the similar reasons, we did not show you how to use Java 2D package that enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and in applets. We want our the materials and examples are less dependent on a particular software product so that you can learn fundamental graphics programming skills. With such skills, you can easily implement most of our examples in virtually any programming language as far as it has a method to draw a straight line and a method to fill a closed polygon.

In this information packed world, an inexhaustible reader can always pick up the missing materials from other reference books. Here are some books we found useful.

  1. Arnold, K and Gosling, J., The Java Programming Language, 2nd ed., 1997, Addison-Wesley.
  2. Deitel, H.M. and Deitel, P.J., Java: How to Program, 2nd ed., 1998, Prentice Hall.
  3. Jackson, J. and McClellan, A., Java by Example 2.2, 3rd ed., 1998, Prentice Hall.
  4. Lemay, L. and Cadenhead, R., Teach Yourself Java 2.2 in 21 Days, 3rd ed., 1998, Sams.