//This applet draws a Bezier curve after user gives the control points
//The Bezier curve is redrawn when user clicks on and moves on of the
//control points
import java.awt.*;
import java.applet.Applet;
public class Bezier extends Applet {
| Point[] coordlist; | //the control points |
| int numpoints; | //number of control points |
| Image offscreenImg; | //used for double buffering |
| double t; | //the time interval |
| double k = .025; | //time step value for drawing curve |
| int moveflag = 5; | //flag to notify if user is moving a point |
| boolean poly = true; | //flag to draw control polygon and points |
| coordlist = new Point[4]; |
| //Create offscreen buffer |
| offscreenImg = createImage(size().width,size().height); |
| offscreenG = offscreenImg.getGraphics(); |
| restart = new Button("Restart"); |
| polygon = new Button("Polygon"); |
| //this method is called internally by repaint() |
| public void update(Graphics g) { |
| public void paint(Graphics g) { |
| setBackground(Color.white); |
| offscreenG.setColor(Color.black); |
| offscreenG.clearRect(0,0,size().width,size().height); |
| //Draw control points and polygon |
| for(int i=0;i<numpoints;i++) { |
| offscreenG.fillOval(coordlist[i].x-2, |
| if(numpoints>1 && i<(numpoints-1)) |
| offscreenG.drawLine(coordlist[i].x,coordlist[i].y, |
| coordlist[i+1].x,coordlist[i+1].y); |
| //Calculate and draw bezier curve |
| //use Berstein polynomials |
| x2=(coordlist[0].x+t*(-coordlist[0].x*3+t*(3*coordlist[0].x- |
| coordlist[0].x*t)))+t*(3*coordlist[1].x+t*(-6*coordlist[1].x+ |
| coordlist[1].x*3*t))+t*t*(coordlist[2].x*3-coordlist[2].x*3*t)+ |
| y2=(coordlist[0].y+t*(-coordlist[0].y*3+t*(3*coordlist[0].y- |
| coordlist[0].y*t)))+t*(3*coordlist[1].y+t*(-6*coordlist[1].y+ |
| coordlist[1].y*3*t))+t*t*(coordlist[2].y*3-coordlist[2].y*3*t)+ |
| offscreenG.drawLine((int)x1,(int)y1,(int)x2,(int)y2); |
| g.drawImage(offscreenImg,0,0,this); |
}
//check if user presses either button
public boolean action(Event e, Object o) {
| if (e.target == restart) { |
| //start all over with no points |
| else if(e.target == polygon) { |
}
public boolean mouseDown(Event evt, int x, int y) {
| Point point = new Point(x,y); |
| //if there are less than four points, add another one |
| coordlist[numpoints] = point; |
| //otherwise, check if user is trying to click on old point |
| for(int i=0;i<numpoints;i++) |
| if(point.equals(new Point(coordlist[i].x+j, |
| public boolean mouseDrag(Event evt, int x, int y) { |
| //check if user is trying to drag an old point |
| if(moveflag < numpoints) { |
| coordlist[moveflag].move(x,y); |
| public boolean mouseUp(Event evt, int x, int y) { |
}