Приглашаем посетить
Бальмонт (balmont.lit-info.ru)

3.3 Displaying graphics and shapes using Java

Table of Contents

Previous Next

3.3 Displaying graphics and shapes using Java

3.3.1 Lines, rectangles, and ovals on Web pages

Before Java, using graphics on Web pages was considered to be a challenge for all Web programmers. Indeed, Java still remains one of the best technologies to provide graphics capabilities on the World Wide Web. At a basic level, Java provides a set of simple functions to draw fundamental graphic shapes including lines, rectangles, and ovals on your Web pages. Some frequently used graphics functions and their calling syntax are listed below:

drawLine(x1,y1,x2,y2)

Draws a line from position (x1,y1) to (x2,y2) in the applet window.

drawRect(x1,y1,w,h)

Draws a rectangle at position (x1,y1) with w (i.e., width) and h (i.e., height) pixels.

fillRect(x1,y1,w,h)

Same as drawRect() except fills rectangle with current color.

clearRect(x1,y1,w,h)

Same as drawRect() except fills rectangle with background color.

drawOval(x,y,w,h)

Draws oval in bounding rectangle of width (w) and height (h) and at position (x,y).

fillOval (x,y,w,h)

Same as drawOval() except fills rectangle with current color.

drawRoundRect( x,y,w,h,arcWidth,arcHeight)

Draws rectangle with rounded corners at position (x,y) with width w and height h. The arcWidth and arcHeight specify the oval fitted into the round corners of the rectangle.

fillRoundRect( x, y, w, h, arcWidth, arcHeight )

Same as drawRoundRect() except fills rectangle with current color.


To show you how to draw these graphics and shapes, consider the following Java program:



Example: Graphics01.java - Using Java Graphics On Web Page I

 1: import java.awt.*;
 2: import java.applet.*;
 3:
 4: public class Graphics01 extends Applet
 5: {
 6:  public void paint(Graphics gg)
 7:  {
 8:    Graphics2D g = (Graphics2D) gg;
 9:
10:    g.setFont(new Font("Arial",Font.BOLD,16));
11:    g.setStroke(new BasicStroke(5));
12:
13:    g.setColor(Color.blue);
14:    g.drawRect(50,40,150,100);
15:    g.drawString("drawRect(50,60,150,100)",30,180);
16:
17:    g.setColor(Color.lightGray);
18:    g.fillRect(270,40,150,100);
19:    g.drawString("fillRect(270,40,150,100)",250,180);
20:
21:    g.setColor(Color.red);
22:    g.drawOval(50,220,150,100);
23:    g.drawString("drawOval(50,220,150,100)",30,360);
24:
25:    g.setColor(Color.magenta);
26:    g.drawRoundRect(270,220,150,100,40,60);
27:    g.drawString("drawRoundRect(270,220,150,", 250,360);
28:    g.drawString("100,40,60)",350,380);
29:   }
30: }

This applet code contains some simple graphic shapes including a rectangle, a filled rectangle, an oval, and a rounded rectangle. After the font setting in line 10, the statement



g.setStroke(new BasicStroke(5));

is used to set the drawing stroke (or line thickness) as 5 pixels. The statement in line 14 draws a rectangle at position (50, 60) and width=150 and height=100. After that, text is printed at the bottom of the shape. Lines 1719 draw a filled rectangle. An oval shape is drawn by the statements in lines 2123. The statement in line 26



g.drawRoundRect(270,220,150,100,40,60);

draws a round rectangle at position (270, 220) with width=150 and height=100. The round corner is in fact an oval with width=40 and height=60.

To run this applet, all you need is to create an XHTML page (e.g., ex03-06.htm) with the following body part:



Listing: ex03-04.txt - Code Fragment For Example ex03-06.htm

1: <body style="font-size:18pt; text-align:center;font-weight:bold">
2:   Some Simple Graphics Shapes<br />Using Java <br />
3:   <applet code="Graphics01.class" width=500 height=400>
4:   </applet>
5: </body>

A screen shot of this example is shown in Fig. 3.11.

Figure 3.11. ex03-06.htm

graphics/03fig11.gif


A page like this for drawing some simple shapes has little practical value. To construct something more practical, let's consider the following example. Suppose you are arranging a meeting for your team via the company Internet (or intranet). Wouldn't it be good if you could make a big cross to cancel out the old date and emphasize a new meeting date? The applet code of this example is given below:



Example: Graphics02.java - Using Java Graphics On Web Page II

 1: import java.awt.*;
 2: import java.applet.*;
 3:
 4: public class Graphics02 extends Applet
 5: {
 6:  public void paint(Graphics gg)
 7:  {
 8:    Graphics2D g = (Graphics2D) gg;
 9:
10:    Font txtFont = new Font("Arial",Font.BOLD,26);
11:    g.setFont(txtFont);
12:
13:    g.setColor(Color.red);
14:    g.setStroke(new BasicStroke(10));
15:    g.drawLine(20,130,280,40);
16:    g.drawLine(20,40,280,130);
17:
18:    g.setColor(Color.blue);
19:    g.drawString("CA Group Memo",20,60);
20:    g.drawString("The 10 th Meeting on",20,90);
21:    g.drawString("Wednesday 10.am, Room C110",20,120);
22:
23:    g.setColor( Color.magenta);
24:    g.fillRect(10,160,400,10);
25:    g.setColor( Color.blue);
26:
27:    g.drawString("CA Group Memo",20,220);
28:    g.drawString("The 10 th Meeting on",20,250);
29:    g.drawString("Friday 2.pm, Room C110",20,280);
30:  }
31: }
32:

There is no new statement in this applet when compared to the previous example. The following statements in lines 1416 draw a big cross:



g.setStroke(new BasicStroke(10));
g.drawLine(20,130,280,40);
g.drawLine(20,40,280,130);

The first statement is to set the stroke (or thickness) of the drawing process. The next two lines draw two lines crossing each other on top of the old meeting date in lines 1921. The fillRect() function in line 24 is used to draw a filled rectangle on the page. Since the height of this rectangle is very thin (10 pixels), the result is similar to drawing a thick line. After this line, the new meeting date is generated as shown in lines 2729.

A page like this could be used in a variety of situations. If you have a listing and require a feature to cross out some of the records, you may need this simple graphical technique. To run this applet, all you need is to create an XHTML page (e.g., ex03-07.htm) with the following body part:



Listing: ex03-05.txt - Code Fragment For Example ex03-07.htm

1: <body style="font-size:18pt; text-align:center;font-weight:bold">
2: Meeting Re-Schedule<br />
3: <applet code="Graphics02.class" width=450 height=300>
4: </applet>
5: </body>

A screen shot of this page is shown in Fig. 3.12.

Figure 3.12. ex03-07.htm

graphics/03fig12.jpg


3.3.2 Polylines and polygons using arrays

In addition to some basic graphics such as lines, rectangles, and ovals, Java also contains functions to handle polylines and polygons. In general, to draw a 2D polyline or polygon, the vertices of the polyline/polygon are first stored in two arrays. One array is for the x-coordinates and the other for the y-coordinates. For example, suppose you have a triangle with the following vertices: (-20,60), (20,60), and (0,100). You can declare two integer arrays such as xData[] and yData[] to store the corresponding coordinates:



int xData[] = {-20, 20, 0};
int yData[] = {60, 60, 100};

The elements of the arrays are



xData[0]= -20, xData[1]= 20, xData[2]= 0
yData[0]= 60, yData[1]= 60, yData[2]= 100

Once the coordinates are stored, you can use the following drawPolyline() function to draw the polyline on the screen:



drawPolyline( xData, yData, 3)

This drawPolyline() function takes three parameters. The first one is the array (i.e., xData[]) storing the x-coordinates of all vertices. The second is the array for the y-coordinates. The third parameter specifies how many points should be used from the arrays. Basically, this function draws all the lines joining the points forming a polyline.

If you want to draw the polygon, you can use the function



drawPolygon( xData, yData, 3)

This function draws the polygon by joining up all the lines including the line between the starting and end points. You can fill the polygon with the current color by issuing the function



fillPolygon( xData, yData, 3)

With Java, you can also define the polygon as an object first and then draw it as an entity. For example, you can use the following code:



int xData[] = {-20, 20, 0};
int yData[] = {60, 60, 100};
Polygon myPoly = new Polygon( xData, yData, 3);
drawPolygon(myPoly);

After the vertices in the first two lines are specified, the third line is used to define a polygon myPoly with Polygon data type. All the vertices of the polygon are defined inside the Polygon() function. The drawPolygon() function is then employed to draw the polygon as an entity.

To put all these into action, consider the Java program Graphics03.java:



Example: Graphics03.java - Polylines and Polygons

 1: import java.awt.*;
 2: import java.applet.*;
 3:
 4: public class Graphics03 extends Applet
 5: {
 6:  public void paint(Graphics gg)
 7:  {
 8:    Graphics2D g = (Graphics2D) gg;
 9:    int ii;
10:    int xData1[]={-20,-60,-20,20,60,20};
11:    int yData1[]={0,40,80,80,40,0};
12:
13:    // Draw a Polyline
14:    g.setStroke(new BasicStroke(5));
15:    g.setColor(Color.blue);
16:    g.translate(80,60);
17:    g.drawPolyline(xData1,yData1,6);
18:
19:    // Draw a Polygon
20:    g.translate(0,100);
21:    g.setColor(Color.red);
22:    g.fillPolygon(xData1,yData1,6);
23:

This is the first part of the Java program Graphics03.java. After all the vertices of the polyline are stored in arrays xData[] and yData[] as in lines 1011, the drawPolyline() function is employed to draw the polyline in line 17 in the color blue. The translation in line 16 is to make sure that the polyline is located at the selected position. Next, we want to draw the same polygon below the polyline. This can be done by the simple translation translate(0,100). This function will move the origin down by 100 pixels. When the fillPolygon() function in line 22 is executed, the polygon is drawn and filled with red color at a position below the polyline.

To demonstrate how to define the polygon data type, consider the second part of the Java program:



Listing: Continuation Of The Java Program Graphics03.java

24:    // Defines a new polygon
25:    int xData2[]={-20,20,0};
26:    int yData2[]={60,60,100};
27:    Polygon myPoly = new Polygon(xData2, yData2, 3);
28:
29:    // Draw Polygon with rotation and random colors
30:    g.translate(180,-10);
31:    for (ii=1;ii<=8;ii++)
32:    {
33:      g.rotate(Math.PI/4.0);
34:      g.setColor( new Color((int) (Math.random()*256),
35:                            (int) (Math.random()*256),
36:                            (int) (Math.random()*256)) );
37:
38:      g.drawPolygon(myPoly);
39:    }
40:
41:    // Draw and fill polygon with Rotation and random colors
42:    g.translate(220,0);
43:    for (ii=1;ii<=8;ii++)
44:    {
45:      g.rotate(Math.PI/4.0);
46:      g.setColor( new Color((int) (Math.random()*256),
47:                            (int) (Math.random()*256),
48:                            (int) (Math.random()*256)) );
49:
50:      g.fillPolygon(myPoly);
51:    }
52:  }
53: }

Lines 2526 specify the two arrays of a polygon. Line 27 declares a polygon using the arrays xData and yData. The translation in line 30 is to move the origin to the right hand side so that the polygon will appear along with the polyline drawn previously. The for-loop and the rotation in lines 3139 draw the polygon eight times with random colors forming a circular shape.

Lines 4251 draw the same set of polygons with random filling colors. The translation in line 42 is used to make sure that the new polygons are drawn at the right hand side of the previous ones. To call this Java code, all you need is a Web page (e.g., ex03-08.htm) that contains the following body element:



Listing: ex03-06.txt - Code Fragment For Example: ex03-08.htm

1: <body style="font-size:18pt; text-align:center;font-weight:bold">
2:     Two Dimensional Polylines and Polygons<br />
3:     Using Java Graphics<br />
4:   <applet code="Graphics03.class" width=580 height=350>
5:   </applet>
6: </body>

This XHTML page calls the program Graphics03.class to draw some simple shapes. A screen shot of this example is shown in Fig. 3.13.

Figure 3.13. Polylines and polygons

graphics/03fig13.gif


3.3.3 Arcs, chords, and pies with Java2D shapes

Similar to the Polygon data type introduced in section 3.3.2, the Java package extends the idea and provides an elegant method for handling more advanced graphics, namely the graphics with Java2D shapes. The basic idea is simple and can be explained by the following processes:

  • define the graphical shapes (e.g., shape_object );

  • use the draw() function to draw the shape (e.g., draw(shape_object) ); or

  • use the fill() function to fill the shape (e.g., fill(shape_object) ).

Shapes can be built in or user defined so that a large number of shapes and graphics can be rendered in a relatively simple way. For example, some of the frequently used Java2D shapes are



Line2D.Double(x1,y1, x2,y2)
Rectangle2D.Double(x1,y1,w,h)
RoundRectangle2D.Double(x1,y1,w,h,arcWidth,arcHeight)

The statements above define a line, a rectangle, and a rounded rectangle respectively. All parameters are the same as the drawLine(), drawRect(), and drawRoundRect() functions mentioned at the beginning of section 3.3. For example, the first statement defines a line from position (x1,y1) to (x2,y2) in double precision (i.e., high accuracy). Once you have defined the shape, you can use the draw() and fill() functions to draw and fill the shapes. For example, the following statement will draw a line from (20,30) to (100,200) on the screen:



draw(new Line2D.Double(20,30,100,200));

Here we are more interested in a new shape called the Java2D arc (or Arc2D). To specify an arc, you can use the function



Arc2D.Double(x, y, w, h, sAngle, rAngle, arc_type)

This function defines an arc in double precision at the position (x, y) with dimension width=w and height=h pixels. The arc starts from an angle sAngle (starting angle) and runs to an angle specified by rAngle (i.e., run angle or arc angle). All angles are measured in degrees. A positive running degree rAngle represents an anti-clockwise arc. Negative rAngle means a clockwise arc. If the parameter w equals h, the arc is a circular arc.

The arc_type can have three options:

Arc2D.OPEN

Draws the arc as a curve.

Arc2D.CHORD

Draws the arc and a line joining the end points.

Arc2D.PIE

Closes the arc with two lines from the center.


Once the arc is defined, you can use the following draw() function to draw the arc:



draw( Arc2D.Double(30,40,140,140,0,120,Arc2D.PIE) )

This statement draws a pie at position (30, 40), with dimension 140 x 140 (width x height). The starting angle is from 0 degrees with a running angle (or arc angle) of 120 degrees. The main purpose of the draw() function is to draw the specified object, which in this case is a pie curve.

If you want to fill the pie shape, you can issue the command



fill( Arc2D.Double(30,40,140,140,0,120,Arc2D.PIE) )

Consider the following Java program:



Example: Arc01.java - Arcs, Chords, And Pies

 1: import java.awt.*;
 2: import java.awt.geom.*;
 3: import java.applet.*;
 4:
 5: public class Arc01 extends Applet
 6: {
 7:  public void paint(Graphics gg)
 8:  {
 9:   Graphics2D g = (Graphics2D) gg;
10:
11:   g.setFont(new Font("Arial",Font.BOLD,16));
12:   g.setStroke(new BasicStroke(5));
13:
14:   g.setColor(Color.red);
15:   g.draw(new Arc2D.Double(30,40,140,140,40,160,Arc2D.OPEN));
16:   g.drawString("draw(new Arc2D.Double(30,40,",0,160);
17:   g.drawString("140,140,40,160,Arc2D.OPEN)",30,180);
18:
19:   g.setColor(Color.blue);
20:   g.draw(new Arc2D.Double(340,40,140,140,40,160,Arc2D.CHORD) );
21:   g.drawString("draw(new Arc2D.Double(340,40,",320,160);
22:   g.drawString("140,140,40,160,Arc2D.CHORD)",360,180);
23:
24:   g.setColor(Color.magenta);
25:   g.draw( new Arc2D.Double(30,200,140,140,40,160,Arc2D.PIE) );
26:   g.drawString("draw(new Arc2D.Double(30,200,",0,370);
27:   g.drawString("140,140,40,160,Arc2D.PIE))",30,390);
28:
29:   g.setColor( ranColor());
30:   g.fill(new Arc2D.Double(340,200,140,140,40,160,Arc2D.PIE) );
31:   g.setColor( ranColor());
32:   g.fill(new Arc2D.Double(340,200,140,140,200,60,Arc2D.PIE) );
33:   g.setColor( ranColor());
34:   g.fill(new Arc2D.Double(340,200,140,140,260,40,Arc2D.PIE) );
35:   g.setColor( ranColor());
36:   g.fill(new Arc2D.Double(340,200,140,140,300,100,Arc2D.PIE) );
37:
38:   g.drawString("Draw and fill a Completed Pie",320,370);
39:  }
40:
41:  public Color ranColor()
42:  {
43:    return(new Color((int) (Math.random()*256),
44:                     (int) (Math.random()*256),
45:                     (int) (Math.random()*256) ));
46:
47:  }
48: }

In order to use Java2D graphics and shapes, you will need to import the package java.awt.geom. With the explanations given previously, this Java program should be quite easy to read. Line 15 draws an open arc from the Java2D shape definition



Arc2D.Double(30,40,140,140,40,160,Arc2D.OPEN)

The Arc2D.OPEN arc type specifies an open arc. Similarly, line 20 draws a chord. A pie is drawn by the statement in line 25. Finally, the statements in lines 2936 draw and fill a completed pie chart. For each part of the pie chart, a random color (i.e., ranColor()) is called so that the color of each pie is different.

The body part of the XHTML page to call this Java code is listed below (ex03-09.htm).



Listing: ex03-07.txt - Code Fragment For Example: ex03-09.htm

1: <body style="font-size:18pt; text-align:center;font-weight:bold">
2:     Graphics: Arc, Chord and Pie<br />Using Java2D Shapes <br />
3:     Using Java2D Shapes <br />
4:   <applet code="Arc01.class" width=580 height=350>
5:   </applet>
6: </body>

This XHTML page calls the program Arc01.class and a screen shot of this example is shown in Fig. 3.14. Before we go on to use Java for business graphics, let's consider how to use Java to draw some more general graphs.

Figure 3.14. Arcs, chords, and pies

graphics/03fig14.gif


3.3.4 Controlling the applet coordinate system

Many graphical formulas or curves have the mathematical form y = f(x). For example, a sine curve is a function where f(x) = sin(x). In general both the variables x and y are real numbers. A real number can be considered as a number with decimals. In terms of computations, they are represented by data of type float or double. In a normal situation, the type double has higher accuracy (or precision) than float. We will not discuss the details or definitions of float or double but simply consider them as a representation of a decimal number.

The graph of the form y = f(x) is usually represented by the x,y coordinate system or (x,f(x)) of real numbers. However, the screen of the computer, or more precisely the applet window, is made up of pixels. Everything displayed on the applet window is referenced by the pixel coordinates. For example, the following applet code defines an applet window with dimension width=600 by height=400 pixels:



<applet code="Line01.class" width=600 height=400></applet>

The top left corner of the applet window is represented by the integer coordinate (0, 0). If you issue the command



drawString("Message at (200,30)",200,30)

the message is displayed at the coordinate 200 pixels to the right and 30 pixels down from the applet window. Compared to the ordinary coordinate system (x,f(x)), they are quite different. Up to this point, all Java graphics and drawings are based on the applet window coordinate system. In order to draw a general graph of the form y = f(x) effectively on a particular area in the applet window, a conversion from the graph coordinate system to a specific applet window area is practically essential. Also, it will give full control over the applet windows including drawing on any scale and multiple displays.

In general, to draw a mathematical formula of the form y = f(x) onto a physical screen or an applet window, you need a method to rescale the ranges of the x- and y-axes or (x,y) coordinates into the integer-based applet window coordinates. First, consider the one-dimensional (1D) case, and suppose the width of the applet window is from A to B. The range of the graph on the x-axis is from minData to maxData. A simple rescaling formula is




       ((t  minData)*B + (maxData  t)*A)
H(t) =
graphics/ccc.gif 

graphics/ccc.gif              (maxData  minData)

where the parameter t is between the values of minData and maxData. For example, suppose you have a function f(x) and the range of x is from minData=0.0 to maxData=3.0. If the applet window's width is from A=0 and B=600 pixels, you have the following rescaling results: H(0.0) = 0 and H(3.0) = 600. That is, the range of the function or data is completely mapped into the applet window's coordinates. Based on this formula, the Java function myScale() is developed as shown below:



public double myScale(int A,int B,double minData,double maxData,double t)
{
     double rDiff;
     rDiff = maxData - minData;
     return( ((t - minData)*B + (maxData -t)*A )/rDiff );
}

This function takes the arguments A, B, minData, maxData, and parameter t. The computation result is returned as a double-precision number.

Apply the myScale() function in both the x- and y-directions, and you will have a general, yet simple method for converting the traditional x,y coordinate system to the top left applet window system. After the conversion, you can apply the Java drawing routines to draw the graph on the applet window. Consider the following Java code:



Example: Coor01.java - Controlling Coordinate Systems (Part One)

 1: import java.awt.*;
 2: import java.awt.geom.*;
 3: import java.applet.*;
 4:
 5: public class Coor01 extends Applet
 6: {
 7:
 8:  public double myScale(int A,int B,double minData,
 9:                        double maxData,double t)
10:  {
11:     double rDiff;
12:     rDiff = maxData - minData;
13:     return( ((t - minData)*B + (maxData -t)*A )/rDiff );
14:  }
15:
16:  public Color ranColor()
17:  {
18:    return(new Color((int) (Math.random()*256),
19:                     (int) (Math.random()*256),
20:                     (int) (Math.random()*256)));
21:
22:  }
23:

This is the first part of the program Coor01.java. This class contains one major function, myScale(), which is used to perform coordinate system rescaling. As you will see even at this simple stage, this function has already provided some practical applications. Consider the test driver paint() function below:



Listing: Continuation Of The Java Program Coor01.java (Part Two)

24:  double xxMax, xxMin, yyMax, yyMin;
25:  int    xxA, xxB, yyA, yyB;
26:  int    xiTmp, yiTmp, ii, noData;
27:  double xTmp, yTmp;
28:
29:  public void paint(Graphics gg)
30:  {
31:   Graphics2D g = (Graphics2D) gg;
32:
33:   // Draw a sine curve with filled rectangles
34:   noData = 24;
35:   xxA = 40; xxB = 560; yyA = 240; yyB = 40;
36:   xxMin = -0.1; xxMax = 1.2; yyMin = -1.2; yyMax = 1.2;
37:
38:   for (ii=0;ii<= noData;ii++)
39:   {
40:     xTmp = (double) ii/noData;
41:     yTmp = Math.sin(2* Math.PI * xTmp );
42:     xiTmp = (int) myScale(xxA,xxB,xxMin,xxMax,xTmp);
43:     yiTmp = (int) myScale(yyA,yyB,yyMin,yyMax,yTmp);
44:     g.setColor(ranColor());
45:     g.fillRect(xiTmp-5,yiTmp-5,10,10);
46:   }
47:   g.setFont(new Font("Arial",Font.BOLD,18));
48:   g.setColor(Color.blue);
49:   g.drawString("f(x) = sin(x)",xiTmp+10,yiTmp-20);
50:
51:   // Draw a cosine curve with filled circles
52:   for (ii=0;ii<= noData;ii++)
53:   {
54:     xTmp = (double) ii/noData;
55:     yTmp = Math.cos(2* Math.PI * xTmp);
56:     xiTmp = (int) myScale(xxA,xxB,xxMin,xxMax,xTmp);
57:     yiTmp = (int) myScale(yyA,yyB,yyMin,yyMax,yTmp);
58:     g.setColor(ranColor());
59:     g.fillOval(xiTmp-5,yiTmp-5,10,10);
60:   }
61:   g.setColor(Color.blue);
62:   g.drawString("f(x) = cos(x)",xiTmp+10,yiTmp-20);
63:  }
64: }
65:

This test paint() function draws two curves. One is the sine function and the other is the cosine function. Lines 3536 define two bounding boxes:



  xxA = 40;     xxB = 560;   yyA = 240;    yyB = 40;
xxMin = -0.1; xxMax = 1.2; yyMin = -1.2; yyMax = 1.2;

The first bounding box is used to specify an area in the applet window. The x-direction is from 40 to 560 pixels moving to the right. The y-direction is from 240 to 40 pixels moving upward. All graphics will be drawn inside this applet window area. The bounding box defined by xxMin, xxMax, yyMin, yyMax will be mapped into the applet window. The for-loop in lines 3846 calculates all the positions (xTmp,yTmp)of a sine curve.

The position is then converted into the integer-based applet window coordinate (xiTmp,yiTmp) in lines 5657. Once you have the window coordinate, the standard fillRect() function can be called to draw a filled rectangle bounding the point as illustrated in line 45. Lines 4749 draw the text "f(x) = sin(x)" at the end of the curve. Lines 5163 draw a cosine curve in a similar manner.

To call this applet, all you need is to write an XHTML page (e.g., ex03-10.htm) with the code



<applet code="Coor01.class" width=600 height=300>
</applet>

A screen shot of this example is shown in Fig. 3.15.

Figure 3.15. ex03-10.htm

graphics/03fig15.gif


For a more general example, let's consider how to draw a set of general data stored in arrays.

3.3.5 Drawing general data on applet windows

Suppose you have a set of data stored in arrays xxData[] and yyData[]. This data set can be drawn on the applet window by the following Java code fragment:



xx0 = (int) myScale(xxA,xxB,xxMin,xxMax,xxData[0]);
yy0 = (int) myScale(yyA,yyB,yyMin,yyMax,yyData[0]);
for(ii=1;ii<noData;ii++)
{
  xxTmp = (int) myScale(xxA,xxB,xxMin,xxMax,xxData[ii]);
  yyTmp = (int) myScale(yyA,yyB,yyMin,yyMax,yyData[ii]);
  Line2D.Double myLine = new Line2D.Double(xx0,yy0,xxTmp,yyTmp);
  g.draw(myLine);
  xx0 = xxTmp; yy0 = yyTmp;
}

The first two lines are used to convert the first data xxData[0] and yyData[0] to the position on the applet window (xx0,yy0). This point will be used as the starting point to draw a line. The for-loop will convert one by one all the consecutive points to the coordinate (xxTmp,yyTmp) on the applet window. Once you have two points, the standard Line2D.Double() function is used to define a line from (xx0,yy0) to (xxTmp,yyTmp). The draw() function draws the line on the window. After finishing one line, the end point (xxTmp,yyTmp) is assigned to the starting point (xx0,yy0) so that the for-loop can continue to draw lines until the data set is exhausted. To see this idea in action, you can develop a Java program called Lines.java. Apart from the class name, the first 23 lines of this program are the same as those in Coor01.java. The remaining coding is listed in ex03-08.txt.



Listing: ex03-08.txt - Code Fragment For The Java Program Lines.java

24:
25:  double[] xxData, yyData;
26:  double xxMax, xxMin, yyMax, yyMin;
27:  int xxA, xxB, yyA, yyB;
28:  int noData;
29:  int ii, xxTmp, yyTmp, xx0,yy0;
30:
31:  public void paint(Graphics gg)
32:  {
33:   Graphics2D g = (Graphics2D) gg;
34:
35:   noData=100;
36:   xxData = new double[noData];
37:   yyData = new double[noData];
38:
39:   for (ii=0;ii<noData;ii++)
40:   {
41:     xxData[ii] = Math.cos(ii* Math.PI *2 /20) * ii/20;
42:     yyData[ii] = Math.sin(ii* Math.PI *2 /20) * ii/20;
43:   }
44:
45:   Dimension d = getSize();
46:   xxA = d.width/8;
47:   xxB = 6 * xxA;
48:   yyA = d.height - d.height/8;
49:   yyB = d.height - 6 * d.height/8;
50:   xxMin = -5; xxMax = 5; yyMin = -5.4; yyMax = 5.4;
51:

This code fragment contains the paint() function. Lines 3537 are used to create the arrays xxData[] and yyData[] with 100 elements. The for-loop in lines 3943 fills the arrays with a spiral formula. In fact, a spiral is basically a circular function with an increasing radius.

Lines 4549 define the display area in the applet window. First, the size of the applet window is retrieved by the statement d=getSize(); so the width and height of the applet window defined in the XHTML page are returned by the variables d.width and d.height.These two variables can be used to define the bounding box in the applet window. In this case, it is slightly smaller than the applet window itself. Line 50 defines the bounding box of the data set.



Listing: Continuation Of The Java Program Lines.java

52:   g.setColor(Color.red);
53:   g.setStroke(new BasicStroke(3));
54:   xx0 = (int) myScale(xxA,xxB,xxMin,xxMax,xxData[0]);
55:   yy0 = (int) myScale(yyA,yyB,yyMin,yyMax,yyData[0]);
56:   for(ii=1;ii<noData;ii++)
57:   {
58:     xxTmp = (int) myScale(xxA,xxB,xxMin,xxMax,xxData[ii]);
59:     yyTmp = (int) myScale(yyA,yyB,yyMin,yyMax,yyData[ii]);
60:     Line2D.Double myLine = new Line2D.Double(xx0,yy0,xxTmp,yyTmp);
61:     g.draw(myLine);
62:   xx0 = xxTmp; yy0 = yyTmp;
63:   }
64:
65:   g.setColor(Color.black);
66:   g.setStroke(new BasicStroke(1));
67:   for(ii=0;ii<noData;ii++)
68:   {
69:     xxTmp = (int) myScale(xxA,xxB,xxMin,xxMax,xxData[ii]);
70:     yyTmp = (int) myScale(yyA,yyB,yyMin,yyMax,yyData[ii]);
71:     g.drawOval(xxTmp-5,yyTmp-5,10,10);
72:   }
73:   g.setFont(new Font("Arial",Font.BOLD,18));
74:   g.setColor(Color.blue);
75:   g.drawString("A Spiral Field",xxTmp+10,yyTmp);
76:  }
77: }

After the color and drawing stroke are set, the statements in lines 5463 draw polylines joining all the points in the data sets xxData[] and yyData[] as described above. The for-loop in lines 6772 draws a circle bounding each data point. Finally, a text "A Spiral Field" is displayed at the end of the spiral. If you have a page with the XHTML applet code (e.g., ex03-11.htm)



<applet code="Lines.class" width=600 height=300></applet>

you can run the applet and see a screen shot as shown in Fig. 3.16.

Figure 3.16. ex03-11.htm

graphics/03fig16.jpg


You now have some idea about Java graphics and it's time to apply what you have learned to some real applications.

    Table of Contents

    Previous Next