Show General Path

This section illustrates you how to create GeneralPath. We have used the class GeneralPath to create three different shapes.

Show General Path

This section illustrates you how to create GeneralPath. We have used the class GeneralPath to create three different shapes.

Show General Path

Show General Path

     

This section illustrates you how to create GeneralPath. We have used the class GeneralPath to create three different shapes. For this, we have create three objects of class GeneralPath i.e, path1, path2, path3.

The method moveTo(25, 35) adds a point to the path by moving to the coordinates (25, 35). The method  lineTo(35, 50) draw a straight line from the current coordinates to the new specified coordinates (35, 50). The method curveTo(20, 100, 110, 60, 40, 100) adds a curved segment, to the path by drawing a curve that intersects both the current coordinates and the new specified coordinates (control points). 

The Vector class represents an array of objects. The method addElement() adds the given component to the vector by increasing its size by one. The method elementAt(i) returns the component at the index.

 

Here is the code of ShowGeneralPath.java 

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.Vector;

public class ShowGeneralPath extends JApplet {
Canvas1 canvas;

public static void main(String[] args) {
  JFrame frame = new JFrame("Show General Paths");
  ShowGeneralPath path = new ShowGeneralPath();
  path.init();
  frame.getContentPane().add(path);
  frame.setSize(280250);
  frame.show();
  }
  public void init() {
  Container container = getContentPane();
  JPanel panel = new JPanel();
  canvas = new Canvas1();
  container.add(canvas);
  }
  class Canvas1 extends Canvas {
  Vector generalPath;

  public Canvas1() {
  setBackground(Color.white);
  setSize(400200);
  generalPath = new Vector();
  GeneralPath path1, path2,path3;

  path1 = new GeneralPath();
  path1.moveTo(2535);
  path1.lineTo(3550);
  path1.lineTo(5020);
  path1.lineTo(8030);
  path1.curveTo(201001106040100);
  generalPath.addElement(path1);

  path2 = new GeneralPath();
  path2.moveTo(12020);
  path2.lineTo(12080);
  path2.lineTo(18020);
  path2.lineTo(18080);
  path2.closePath();
  generalPath.addElement(path2);

  path3 = new GeneralPath();
  path3.moveTo(50120);
  path3.lineTo(70180);
  path3.lineTo(20140);
  path3.lineTo(80140);
  path3.lineTo(30180);
  path3.closePath();
  generalPath.addElement(path3);
 }
  public void paint(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;
 for (int i = 0; i < generalPath.size(); i++) {
  g2d.setPaint(Color.red);
  g2d.draw((GeneralPath) generalPath.elementAt(i));
  }
  }
  }
}

Output will be displayed as:

Download Source Code