The user has to pick 4 points by clicking anywhere in the frame, and then the program is supposed to draw a Bezier curve. I've also included a method that draws small circles where the user click so it's easier to see.
I'm not getting any errors, but the curve is just not showing. Obviously, I'm missing something, but I can't figure out what.
Code:
public class Splines {
public Splines(){
JFrame frame = new JFrame("Bezier curves");
frame.add(new draw());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class draw extends JPanel implements MouseListener{
Point[] controlPoints = new Point[100];
ArrayList<Point> punkter = new ArrayList<>();
int pSize = punkter.size();
public draw(){
addMouseListener(this);
}
@Override
public void mousePressed(MouseEvent e) {
if (pSize==4) drawBezier(pSize,4,getGraphics());
drawPoint(e);
pSize++;
}
//Method drawing points to visualize the control points
public void drawPoint(MouseEvent evt){
Graphics g = getGraphics();
Graphics2D g2d = (Graphics2D) g;
punkter.add(new Point(evt.getX(), evt.getY()));
g2d.setColor(Color.red);
g2d.fillOval(punkter.get(pSize).x, punkter.get(pSize).y, 5, 5);
controlPoints[pSize] = punkter.get(pSize);
}
public void drawBezier(int i, int n, Graphics g) {
int j;
double t, delta;
Point curvePoints[] = new Point[n + 1];
delta = 1.0 / n;
for (j = 0; j <= n; j++) {
t = j * delta;
curvePoints[j] = new Point();
curvePoints[j].x = (int) Math.round(controlPoints[i - 3].x * (1.0 - t) * (1.0 - t) * (1.0 - t)
+ controlPoints[i - 2].x * 3.0 * t * (1.0 - t) * (1.0 - t)
+ controlPoints[i - 1].x * 3.0 * t * t * (1.0 - t)
+ controlPoints[i].x * t * t * t);
curvePoints[j].y = (int) Math.round(controlPoints[i - 3].y * (1.0 - t) * (1.0 - t) * (1.0 - t)
+ controlPoints[i - 2].y * 3.0 * t * (1.0 - t) * (1.0 - t)
+ controlPoints[i - 1].y * 3.0 * t * t * (1.0 - t)
+ controlPoints[i].y * t * t * t);
}
g.setColor(Color.red);
for (j = 0; j < n; j++)
g.drawLine(curvePoints[j].x, curvePoints[j].y, curvePoints[j + 1].x, curvePoints[j + 1].y);
} // End drawBezier
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
}//End draw class
public static void main(String[] args) {
new Splines();
}//End main method
}//End Spline class