Drawing Polygons
One approach is to use multiple calls to drawLine() to draw a sequence of straight line segments that outlines the desired shape.
But a faster approach is instead to use a single call to drawPolyline(). This will speed up the drawing since the process needs only one invocation of the method, rather than one for each line segment.
Code:
import javax.swing.*;
import java.awt.*;
/** Example demonstrating drawPolyline().*/
public class Polygon1Applet extends JApplet
{
public void init () {
Container content_pane = getContentPane ();
int width = getSize ().width;
int height= getSize ().height;
int num_points = 21;
// Create an instance of DrawingPanel
Polygon1Panel polygon1_panel =
new Polygon1Panel (width,height,num_points);
// Add the DrawingPanel to the contentPane.
content_pane.add (polygon1_panel);
}
}
/** Draw a polygon with drawPolyline() on
* this JPanel subclass. **/
class Polygon1Panel extends JPanel
{
int fWidth,fHeight;
int fNumPoints;
double fFactor;
Polygon1Panel (int width, int height, int nPoints) {
fNumPoints = nPoints;
fWidth = width;
fHeight= height;
fFactor = 2.0 * Math.PI / fWidth;
} // ctor
public void paintComponent (Graphics g) {
// First paint background unless you will
// paint whole area yourself.
super.paintComponent (g);
// Create arrays of points for each
// segment of the polygon
int [] x = new int[fNumPoints];
int [] y = new int[fNumPoints];
// Select horizontal step size
double x_del= ((double)fWidth)/ (fNumPoints-1);
// Find coordinates of the display center
int x_offset = fWidth/2;
int y_offset = fHeight/2;
// Choose amplitude for the sine curve
int amp = (int) (y_offset * 0.9);
// Create a sine curve from a sequence
// of short line segments
for (int i=0; i < fNumPoints; i++) {
x[i] = (int) (i * x_del);
y[i] = (int) (amp * Math.sin (fFactor * x[i]) )
+ y_offset;
}
// Set the line color to red
g.setColor (Color.red);
// Draw curve with single call to drawPolyline
g.drawPolyline (x,y,fNumPoints);
// Change the line color and draw the x-y axes
g.setColor (Color.green);
g.drawLine (0,y_offset,fWidth-1,y_offset);
g.drawLine (x_offset,0,x_offset,fHeight-1);
} // paintComponent
} // class Polygon1Panel
The method
drawPolygon(int[] x, int[] y, int nPoints)
will work similarly, except it will connect the last point to the first if they are not the identical.
An interesting overriden version of this method
drawPolygon(Polygon poly)
uses an instance of the Polygon class to hold the points.
Bookmarks