Results 1 to 10 of 10
  1. #1
    murdplacid is offline Member
    Join Date
    Sep 2010
    Posts
    9
    Rep Power
    0

    Default Creation of a curved surface as an airfoil using java AWT

    I am trying to create an airfoil. An airfoil is nothing but the crossection of the wing of an airplane or a turbine blade. I am very new to AWT in java but i have tried to write a code which generates the coordinates and draws a curve using those points. the code is given below

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    
    
    public class DrawCurve extends JPanel implements ActionListener {
    ButtonManager buttonManager;
    Path2D.Double path;
    Point2D.Double[] points;
    Line2D.Double[] connectors;
    boolean showConnections= false;
    boolean removePoint= false;
    boolean firstTime= true;
    final double Factor = 50.0D;
    
    
    DrawCurve() {
    
    float maxcamber,position,thickness;
    int datapts;
    double x1,y1;
    maxcamber=0.08F;position=5.0F;thickness=0.12F;data pts=25;
    int i=1;
    double yt[]=new double [100];
    double yc[]=new double [100];
    
    double xu[]=new double [100];
    double yu[]=new double [100];
    double xl[]=new double [100];
    double yl[]=new double [100];
    double x[]=new double [100];
    
    for(i=1;i<=datapts;i++)
    {
    
    x13.141562/180)*(i-1)*(90/(datapts-1)));
    x[i]=(1-Math.cos(x1));
    yt[i]=(thickness/0.2)*((0.2969*Math.pow(x[i],0.5))-(0.126*x[i])-(0.3516*Math.pow(x[i],2))+(0.2843*Math.pow(x[i],3))-(0.1015*Math.pow(x[i],4)));
    if(x[i]<(position/10))
    {
    yc[i]=(maxcamber/(Math.pow((position/10),2))*((2*(position/10)*x[i])-(Math.pow(x[i],2))));
    }
    else
    {
    yc[i]=(maxcamber/(Math.pow(1-(position/10),2)))*((1-(2*(position/10)))+(2*(position/10)*x[i])-Math.pow(x[i],2));
    }
    
    xu[i]=x[i]-yt[i]*(Math.sin(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
    yu[i]=yc[i]+yt[i]*(Math.cos(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
    xl[i]=x[i]+yt[i]*(Math.sin(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
    yl[i]=yc[i]-yt[i]*(Math.cos(Math.atan((yc[i+1]-yc[i]/(x[i+1]-x[i])))));
    // System.out.println("x :"+x [i]);
    //System.out.println("yt :"+yt [i]);
    //System.out.println("yc :"+yc [i]);
    System.out.println("xu :"+xu [i]);
    System.out.println("yu :"+yu [i]);
    System.out.println("xl :"+xl [i]);
    System.out.println("yl :"+yl [i]);
    System.out.println(" ");
    
    
    /*double[][] cds= { {0,0},{0.00378,0.01779},{0.02536,0.03931}, {0.06478,0.06320},{0.12172,0.08733},
    {0.19533,0.10908},{0.2, 8417,12564},{0.38625,0.13435},{0.49906,0.13293},
    {0.61979,0.11971},{0.74551,0.09361},{0.87332,0.054 12 },{1.0036,0.00121} };*/
    
    double[][] cds= {{xu[i],yu[i]},{xl[i],yl[i]}};
    System.out.println("cds :"+cds[i][i]);
    
    points = new Point2D.Double[cds.length];
    
    for(int j = 0; j < cds.length; j++) { // NOTE 1 based? -1 stops short here also
    points[j] = new Point2D.Double(Factor * cds[j][0] + Factor, Factor * cds[j][1] + Factor);
    }
    }//for loop end
    /*Path2D.Double*/ path = new Path2D.Double();
    System.out.println("1path bnds=" + path.getBounds());
    }
    
    
    
    public void actionPerformed(ActionEvent e) {
    System.out.println("aP e=" + e);
    String ac = e.getActionCommand();
    if(ac.equals("add")) {
    connectors = new Line2D.Double[points.length-1];
    showConnections = true;
    repaint();
    }
    if(ac.equals("cancel")) {
    showConnections = false;
    removePoint = false;
    repaint();
    }
    if(ac.equals("remove")) {
    removePoint = true;
    }
    }
    
    public void addPoint(Point2D.Double p, int index) {
    int size = points.length;
    Point2D.Double[] temp = new Point2D.Double[size+1];
    System.arraycopy(points, 0, temp, 0, index);
    temp[index] = p;
    System.arraycopy(points, index, temp, index+1, size-index);
    points = temp;
    buttonManager.reset();
    showConnections = false;
    setPath();
    repaint();
    }
    
    public void removePoint(Point2D.Double p) {
    int size = points.length;
    Point2D.Double[] temp = new Point2D.Double[size-1];
    for(int j = 0, k = 0; j < size; j++) {
    if(points[j] == p)
    continue;
    temp[k++] = points[j];
    }
    points = temp;
    buttonManager.reset();
    removePoint = false;
    setPath();
    repaint();
    }
    
    public void setPoint(Point2D.Double p,double x,double y) {
    p.setLocation(x, y);
    setPath();
    repaint();
    }
    
    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    System.out.println("pC path bnds=" + path.getBounds()); //pC path bnds=java.awt.Rectangle[x=0,y=0,width=0,height=0]
    Graphics2D g2 = (Graphics2D)g;
    Path2D.Double path = new Path2D.Double();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONT ROL,
    RenderingHints.VALUE_STROKE_PURE);
    if(firstTime) {
    firstTime = false;
    setPath();
    }
    g2.setPaint(Color.green.darker());
    
    g2.draw(path); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ????
    
    g2.setPaint(Color.red);
    for(int j = 0; j < points.length; j++) {
    mark(g2, points[j]);
    }
    // For adding a point.
    if(showConnections) {
    g2.setPaint(Color.yellow);
    for(int j = 0; j < points.length-1; j++) {
    connectors[j] = new Line2D.Double(points[j], points[j+1]);
    g2.draw(connectors[j]);
    }
    }
    } // end paintComponent()
    
    /**
    * P(t) = B(n,0)*P0 + B(n,1)*P1 + ... + B(n,n)*Pn
    * 0 <= t <= 1
    *
    * B(n,m) = mth coefficient of nth degree Bernstein polynomial
    * = C(n,m) * t^(m) * (1 - t)^(n-m)
    * C(n,m) = Combinations of n things, taken m at a time
    * = n! / (m! * (n-m)!)
    */
    private void setPath() {
    System.out.println("2path bnds=" + path.getBounds());
    path.reset();
    int n = points.length;
    int w = getWidth();
    for(int j = 0; j <= w; j++) {
    double t = (double)j/w; // [0 <= t <= 1.0]
    double x = 0;
    double y = 0;
    for(int k = 1; k < n; k++) {
    // System.out.println("k=" + k + " points[k]=" + points[k]); //k=0 points[k]=null
    x += B(n-1,k,t)*points[k].x;
    y += B(n-1,k,t)*points[k].y;
    }
    if(j > 0)
    path.lineTo(x,y);
    else
    path.moveTo(x,y);
    }
    } // end setPath()
    
    private double B(int n, int m, double t) {
    return C(n,m) * Math.pow(t, m) * Math.pow(1.0 - t, n-m);
    }
    
    private double C(int n, int m) {
    return factorial(n) / (factorial(m)*factorial(n-m));
    }
    
    private double factorial(int n) {
    return (n > 1) ? n*factorial(n-1) : 1;
    }
    
    private void mark(Graphics2D g2, Point2D.Double p) {
    g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
    }
    
    private JPanel getButtonPanel() {
    buttonManager = new ButtonManager();
    String[] ids = { "add", "cancel", "remove" };
    JPanel panel = new JPanel();
    for(int j = 0; j < ids.length; j++) {
    JButton button = new JButton(ids[j]);
    button.setEnabled(j != 1);
    buttonManager.add(button);
    button.setActionCommand(ids[j]);
    button.addActionListener(this);
    panel.add(button);
    }
    return panel;
    }
    //----------------------------------------------------------------
    public static void main(String[] args) {
    DrawCurve test = new DrawCurve();
    PointMover mover = new PointMover(test);
    test.addMouseListener(mover);
    test.addMouseMotionListener(mover);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(test);
    f.add(test.getButtonPanel(), "Last");
    f.setSize(500,500);
    f.setLocation(200,200);
    f.setVisible(true);
    }
    //-------------------------------------------------------
    static class PointMover extends MouseInputAdapter {
    DrawCurve component;
    Point2D.Double selectedPoint;
    Cursor cursor;
    Cursor defaultCursor = Cursor.getDefaultCursor();
    Point2D.Double offset = new Point2D.Double();
    boolean dragging = false;
    final int PROX_DIST = 5;
    
    PointMover(DrawCurve cf) {
    component = cf;
    BufferedImage image = getImage();
    Point hotspot = new Point(17,17);
    cursor = Toolkit.getDefaultToolkit().createCustomCursor(ima ge, hotspot, null);
    }
    
    public void mousePressed(MouseEvent e) {
    if(selectedPoint != null) {
    if(component.removePoint) { // remove
    component.removePoint(selectedPoint);
    } else { // drag
    offset.x = e.getX() - selectedPoint.x;
    offset.y = e.getY() - selectedPoint.y;
    dragging = true;
    }
    } else if(component.showConnections) { // add
    Point p = e.getPoint();
    Line2D.Double[] lines = component.connectors;
    for(int j = 0; j < lines.length; j++) {
    if(lines[j].ptSegDist(p) < PROX_DIST) {
    component.addPoint(p, j+1);
    break;
    }
    }
    }
    }
    
    public void mouseReleased(MouseEvent e) {
    dragging = false;
    }
    
    public void mouseDragged(MouseEvent e) {
    if(dragging) {
    double x = e.getX() - offset.x;
    double y = e.getY() - offset.y;
    component.setPoint(selectedPoint, x, y);
    }
    }
    
    /** For point selection. */
    public void mouseMoved(MouseEvent e) {
    Point p = e.getPoint();
    Point2D.Double[] pts = component.points;
    boolean hovering = false;
    for(int j = 0; j < pts.length; j++) {
    if(pts[j].distance(p) < PROX_DIST) {
    hovering = true;
    if(selectedPoint != pts[j]) {
    selectedPoint = pts[j];
    component.setCursor(cursor);
    break;
    }
    }
    }
    
    if(!hovering && selectedPoint != null) {
    selectedPoint = null;
    component.setCursor(defaultCursor);
    }
    }
    
    private BufferedImage getImage() {
    int w = 27, h = 27,
    type = BufferedImage.TYPE_INT_ARGB_PRE;
    BufferedImage image = new BufferedImage(w, h, type);
    Graphics2D g2 = image.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(new Color(0x333333));
    g2.draw(new Line2D.Double(w/2, 0, w/2, ); // n
    g2.draw(new Line2D.Double(0, h/2, 8, h/2)); // w
    g2.draw(new Line2D.Double(w/2, h-8, w/2, h)); // s
    g2.draw(new Line2D.Double(w-8, h/2, w, h/2)); // e
    g2.dispose();
    return image;
    }
    }
    
    //----------------------------------------
    class ButtonManager implements ActionListener {
    JButton[] buttons = new JButton[0];
    
    public void actionPerformed(ActionEvent e) {
    String ac = e.getActionCommand();
    if(ac.equals("add")) {
    getButton("remove").setEnabled(false);
    enable(true);
    } else if(ac.equals("remove")) {
    getButton("add").setEnabled(false);
    enable(true);
    } else {
    
    reset();
    }
    }
    
    public void reset() {
    getButton("add").setEnabled(true);
    
    getButton("remove").setEnabled(true);
    enable(false);
    }
    
    private void enable(boolean enable) {
    getButton("cancel").setEnabled(enable);
    }
    
    public void add(JButton button) {
    button.addActionListener(this);
    int size = buttons.length;
    JButton[] temp = new JButton[size+1];
    System.arraycopy(buttons, 0, temp, 0, size);
    temp[size] = button;
    buttons = temp;
    }
    
    private JButton getButton(String target) {
    for(int j = 0; j < buttons.length; j++) {
    if(buttons[j].getActionCommand().equals(target))
    return buttons[j];
    }
    return null;
    }
    }
    } // end class
    i am getting an error with one statement but when i ignore it the applet is displayed but with only 2 points.

    I tried to manually specify the coordinates as double datatype then i get the curve

    Can some on help me out with this. ...... Please if u can help me out with this.
    Last edited by Fubarable; 09-21-2010 at 05:52 PM. Reason: Moderator edit: quote tags changed to code tags -- but posted code is unformatted :(

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Hello and welcome to the forum. I've edited your post to change your quote tags to code tags, but your code is still very difficult to read as it is unformatted (all left-justified). This suggests that you didn't post code from your editor or IDE but rather code obtained from another post?

    I suggest you edit your post above (press the edit button at the bottom of it), and paste in formatted code. Also, given the size of your posted code, you'll likely get better help if you give us more information such as the exact error message and the location of the error. Also, have you posted this same question in other forums? If so, please post links to these other posts.

    Much luck and again welcome.

  3. #3
    paul pasciak is offline Senior Member
    Join Date
    Jul 2008
    Posts
    125
    Rep Power
    0

    Default With code tags it looks like this

    This project looks interesting, so I put it in code tags



    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    
    
    public class DrawCurve extends JPanel implements ActionListener {
      ButtonManager buttonManager;
      Path2D.Double path;
      Point2D.Double[] points;
      Line2D.Double[] connectors;
      boolean showConnections = false;
      boolean removePoint     = false;
      boolean firstTime       = true;
      final double Factor     = 50.0D;
    
    
      DrawCurve(){
    
        float maxcamber,position,thickness;
        int datapts;
        double x1,y1;
        maxcamber=0.08F;position=5.0F;thickness=0.12F;data pts=25;
        int i=1;
        double yt[]=new double [100];
        double yc[]=new double [100];
    
        double xu[]=new double [100];
        double yu[]=new double [100];
        double xl[]=new double [100];
        double yl[]=new double [100];
        double x[] =new double [100];
    
        for(i=1;i<=datapts;i++){
    
          x13.141562/180)*(i-1)*(90/(datapts-1)));
          x[i]  = (1-Math.cos(x1));
          yt[i] = (thickness/0.2)*((0.2969*Math.pow(x[i],0.5))-(0.126*x[i])-
                  (0.3516*Math.pow(x[i],2))+(0.2843*Math.pow(x[i],3))-
                  (0.1015*Math.pow(x[i],4)));
          if(x[i]<(position/10)){
            yc[i] = (maxcamber/(Math.pow((position/10),2))*
                    ((2*(position/10)*x[i])-(Math.pow(x[i],2))));
          }
          else{
            yc[i] = (maxcamber/(Math.pow(1-(position/10),2)))*((1-(2*(position/10)))+
                    (2*(position/10)*x[i])-Math.pow(x[i],2));
          }
    
          xu[i]=x[i]-yt[i]*(Math.sin(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
          yu[i]=yc[i]+yt[i]*(Math.cos(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
          xl[i]=x[i]+yt[i]*(Math.sin(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
          yl[i]=yc[i]-yt[i]*(Math.cos(Math.atan((yc[i+1]-yc[i]/(x[i+1]-x[i])))));
          // System.out.println("x :"+x [i]);
          //System.out.println("yt :"+yt [i]);
          //System.out.println("yc :"+yc [i]);
          System.out.println("xu :"+xu [i]);
          System.out.println("yu :"+yu [i]);
          System.out.println("xl :"+xl [i]);
          System.out.println("yl :"+yl [i]);
          System.out.println(" ");
    
          /*double[][] cds= { {0,0},               {0.00378, 0.01779},
                              {0.02536,  0.03931}, {0.06478, 0.06320},
                              {0.12172,  0.08733}, {0.19533, 0.10908},
                              {0.2,8417,   12564}, {0.38625, 0.13435},
                              {0.49906,  0.13293}, {0.61979, 0.11971},
                              {0.74551,  0.09361}, {0.87332, 0.05412},
                              {1.0036,   0.00121} };*/
    
          double[][] cds= {{xu[i],yu[i]},{xl[i],yl[i]}};
          System.out.println("cds :"+cds[i][i]);
    
          points = new Point2D.Double[cds.length];
    
          for(int j = 0; j < cds.length; j++){
            // NOTE 1 based? -1 stops short here also
            points[j] = new Point2D.Double(Factor * cds[j][0] + Factor,
                                           Factor * cds[j][1] + Factor);
          }
        }//for loop end
        /*Path2D.Double*/ path = new Path2D.Double();
        System.out.println("1path bnds=" + path.getBounds());
      }
    
    
    
      public void actionPerformed(ActionEvent e){
        System.out.println("aP e=" + e);
        String ac = e.getActionCommand();
        if(ac.equals("add")) {
          connectors = new Line2D.Double[points.length-1];
          showConnections = true;
          repaint();
        }
        if(ac.equals("cancel")){
          showConnections = false;
          removePoint = false;
          repaint();
        }
        if(ac.equals("remove")){
          removePoint = true;
        }
      }
    
      public void addPoint(Point2D.Double p, int index) {
        int size = points.length;
        Point2D.Double[] temp = new Point2D.Double[size+1];
        System.arraycopy(points, 0, temp, 0, index);
        temp[index] = p;
        System.arraycopy(points, index, temp, index+1, size-index);
        points = temp;
        buttonManager.reset();
        showConnections = false;
        setPath();
        repaint();
      }
    
      public void removePoint(Point2D.Double p) {
        int size = points.length;
        Point2D.Double[] temp = new Point2D.Double[size-1];
        for(int j = 0, k = 0; j < size; j++) {
          if(points[j] == p)
            continue;
          temp[k++] = points[j];
        }
        points = temp;
        buttonManager.reset();
        removePoint = false;
        setPath();
        repaint();
      }
    
      public void setPoint(Point2D.Double p,double x,double y) {
        p.setLocation(x, y);
        setPath();
        repaint();
      }
    
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("pC path bnds=" + path.getBounds());
    //pC path bnds=java.awt.Rectangle[x=0,y=0,width=0,height=0]
        Graphics2D g2 = (Graphics2D)g;
        Path2D.Double path = new Path2D.Double();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
        RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONT ROL,
        RenderingHints.VALUE_STROKE_PURE);
        if(firstTime) {
          firstTime = false;
          setPath();
        }
        g2.setPaint(Color.green.darker());
    
        g2.draw(path); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ????
    
        g2.setPaint(Color.red);
        for(int j = 0; j < points.length; j++) {
          mark(g2, points[j]);
        }
        // For adding a point.
        if(showConnections) {
          g2.setPaint(Color.yellow);
          for(int j = 0; j < points.length-1; j++) {
            connectors[j] = new Line2D.Double(points[j], points[j+1]);
            g2.draw(connectors[j]);
          }
        }
      } // end paintComponent()
    
      /**
       * P(t) = B(n,0)*P0 + B(n,1)*P1 + ... + B(n,n)*Pn
       * 0 <= t <= 1
       *
       * B(n,m) = mth coefficient of nth degree Bernstein polynomial
       *        = C(n,m) * t^(m) * (1 - t)^(n-m)
       * C(n,m) = Combinations of n things, taken m at a time
       *        = n! / (m! * (n-m)!)
       */
      private void setPath() {
        System.out.println("2path bnds=" + path.getBounds());
        path.reset();
        int n = points.length;
        int w = getWidth();
        for(int j = 0; j <= w; j++) {
          double t = (double)j/w; // [0 <= t <= 1.0]
          double x = 0;
          double y = 0;
          for(int k = 1; k < n; k++) {
            // System.out.println("k=" + k + " points[k]=" +
            //                     points[k]); //k=0 points[k]=null
            x += B(n-1,k,t)*points[k].x;
            y += B(n-1,k,t)*points[k].y;
          }
          if(j > 0)
            path.lineTo(x,y);
          else
            path.moveTo(x,y);
        }
      } // end setPath()
    
      private double B(int n, int m, double t) {
        return C(n,m) * Math.pow(t, m) * Math.pow(1.0 - t, n-m);
      }
    
      private double C(int n, int m) {
        return factorial(n) / (factorial(m)*factorial(n-m));
      }
    
      private double factorial(int n) {
        return (n > 1) ? n*factorial(n-1) : 1;
      }
    
      private void mark(Graphics2D g2, Point2D.Double p) {
        g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
      }
    
      private JPanel getButtonPanel() {
        buttonManager = new ButtonManager();
        String[] ids  = { "add", "cancel", "remove" };
        JPanel panel  = new JPanel();
        for(int j = 0; j < ids.length; j++) {
          JButton button = new JButton(ids[j]);
          button.setEnabled(j != 1);
          buttonManager.add(button);
          button.setActionCommand(ids[j]);
          button.addActionListener(this);
          panel.add(button);
        }
        return panel;
      }
    //------------------------------------------------------
      public static void main(String[] args) {
        DrawCurve test = new DrawCurve();
        PointMover mover = new PointMover(test);
        test.addMouseListener(mover);
        test.addMouseMotionListener(mover);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(test);
        f.add(test.getButtonPanel(), "Last");
        f.setSize(500,500);
        f.setLocation(200,200);
        f.setVisible(true);
      }
    //------------------------------------------------------
      static class PointMover extends MouseInputAdapter {
        DrawCurve component;
        Point2D.Double selectedPoint;
        Cursor cursor;
        Cursor defaultCursor = Cursor.getDefaultCursor();
        Point2D.Double offset = new Point2D.Double();
        boolean dragging = false;
        final int PROX_DIST = 5;
    
        PointMover(DrawCurve cf) {
        component = cf;
        BufferedImage image = getImage();
        Point hotspot = new Point(17,17);
        cursor = Toolkit.getDefaultToolkit().
                         createCustomCursor(ima ge, hotspot, null);
      }
    
      public void mousePressed(MouseEvent e) {
        if(selectedPoint != null) {
          if(component.removePoint) { // remove
            component.removePoint(selectedPoint);
          }
          else { // drag
            offset.x = e.getX() - selectedPoint.x;
            offset.y = e.getY() - selectedPoint.y;
            dragging = true;
          }
        }
        else if(component.showConnections) { // add
          Point p = e.getPoint();
          Line2D.Double[] lines = component.connectors;
          for(int j = 0; j < lines.length; j++) {
            if(lines[j].ptSegDist(p) < PROX_DIST) {
              component.addPoint(p, j+1);
              break;
            }
          }
        }
      }
    
      public void mouseReleased(MouseEvent e) {
        dragging = false;
      }
    
      public void mouseDragged(MouseEvent e) {
        if(dragging) {
          double x = e.getX() - offset.x;
          double y = e.getY() - offset.y;
          component.setPoint(selectedPoint, x, y);
        }
      }
    
      /** For point selection. */
      public void mouseMoved(MouseEvent e) {
        Point p = e.getPoint();
        Point2D.Double[] pts = component.points;
        boolean hovering = false;
        for(int j = 0; j < pts.length; j++) {
          if(pts[j].distance(p) < PROX_DIST) {
            hovering = true;
            if(selectedPoint != pts[j]) {
              selectedPoint = pts[j];
              component.setCursor(cursor);
              break;
            }
          }
        }
    
        if(!hovering && selectedPoint != null) {
          selectedPoint = null;
          component.setCursor(defaultCursor);
        }
      }
    
      private BufferedImage getImage() {
        int w = 27, h = 27,
        type = BufferedImage.TYPE_INT_ARGB_PRE;
        BufferedImage image = new BufferedImage(w, h, type);
        Graphics2D g2       = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
        RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(new Color(0x333333));
        g2.draw(new Line2D.Double(w/2, 0,   w/2,     ); // n
        g2.draw(new Line2D.Double(0,   h/2, 8,   h/2)); // w
        g2.draw(new Line2D.Double(w/2, h-8, w/2, h  )); // s
        g2.draw(new Line2D.Double(w-8, h/2, w,   h/2)); // e
        g2.dispose();
        return image;
      }
    }
    
    //----------------------------------------
    class ButtonManager implements ActionListener {
      JButton[] buttons = new JButton[0];
    
      public void actionPerformed(ActionEvent e) {
        String ac = e.getActionCommand();
        if(ac.equals("add")) {
          getButton("remove").setEnabled(false);
          enable(true);
        }
        else if(ac.equals("remove")) {
          getButton("add").setEnabled(false);
          enable(true);
        }
        else {
          reset();
        }
      }
    
      public void reset() {
        getButton("add").setEnabled(true);
    
        getButton("remove").setEnabled(true);
        enable(false);
      }
    
      private void enable(boolean enable) {
        getButton("cancel").setEnabled(enable);
      }
    
      public void add(JButton button) {
        button.addActionListener(this);
        int size       = buttons.length;
        JButton[] temp = new JButton[size+1];
        System.arraycopy(buttons, 0, temp, 0, size);
        temp[size] = button;
        buttons    = temp;
      }
    
      private JButton getButton(String target) {
        for(int j = 0; j < buttons.length; j++) {
          if(buttons[j].getActionCommand().equals(target))
            return buttons[j];
          }
          return null;
        }
      }
    } // end class

  4. #4
    murdplacid is offline Member
    Join Date
    Sep 2010
    Posts
    9
    Rep Power
    0

    Default help with this code

    Its is the same code that i had posted on other forums too. I just copied and pasted from the old threads i had posted earlier. i am very new to java forums and know very little about code tags.



    Thank u for helping me by putting the code tags. the main issue arises in the upper part.

    Java Code:
    DrawCurve() {
    
    	float maxcamber,position,thickness;
    	int datapts;
            double x1,y1;
            maxcamber=0.08F;position=5.0F;thickness=0.12F;datapts=25;
            int i=1;
            double yt[]=new double [100];
            double yc[]=new double [100];
    
            double xu[]=new double [100];
            double yu[]=new double [100];
            double xl[]=new double [100];
            double yl[]=new double [100];
            double x[]=new double [100];
    	
            for(i=1;i<=datapts;i++)
            {
    	
    	x1=((3.141562/180)*(i-1)*(90/(datapts-1)));
    	x[i]=(1-Math.cos(x1));
    	yt[i]=(thickness/0.2)*((0.2969*Math.pow(x[i],0.5))-(0.126*x[i])-(0.3516*Math.pow(x[i],2))+(0.2843*Math.pow(x[i],3))-(0.1015*Math.pow(x[i],4)));
            if(x[i]<(position/10))
    	{
                yc[i]=(maxcamber/(Math.pow((position/10),2))*((2*(position/10)*x[i])-(Math.pow(x[i],2))));
    	}
    	else
    	{
                yc[i]=(maxcamber/(Math.pow(1-(position/10),2)))*((1-(2*(position/10)))+(2*(position/10)*x[i])-Math.pow(x[i],2));
    	}
    	
            xu[i]=x[i]-yt[i]*(Math.sin(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
            yu[i]=yc[i]+yt[i]*(Math.cos(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
            xl[i]=x[i]+yt[i]*(Math.sin(Math.atan((yc[i+1]-yc[i])/(x[i+1]-x[i]))));
            yl[i]=yc[i]-yt[i]*(Math.cos(Math.atan((yc[i+1]-yc[i]/(x[i+1]-x[i])))));
           // System.out.println("x  :"+x  [i]);
    	//System.out.println("yt :"+yt  [i]);
    	//System.out.println("yc :"+yc  [i]);
    	System.out.println("xu :"+xu  [i]);
    	System.out.println("yu :"+yu  [i]);
    	System.out.println("xl :"+xl  [i]);
    	System.out.println("yl :"+yl  [i]);
    	System.out.println("   ");
            
    
    /*double[][] cds= { {0,0},{0.00378,0.01779},{0.02536,0.03931}, {0.06478,0.06320},{0.12172,0.08733},
                      {0.19533,0.10908},{0.2, 8417,12564},{0.38625,0.13435},{0.49906,0.13293},
                      {0.61979,0.11971},{0.74551,0.09361},{0.87332,0.05412 },{1.0036,0.00121} };*/
    
    double[][] cds= {{xu[i],yu[i]},{xl[i],yl[i]}};
    System.out.println("cds :"+cds[i][i]);
    
    points = new Point2D.Double[cds.length];
    
    for(int j = 0; j < cds.length; j++) {  // NOTE 1 based?  -1 stops short here also
       points[j] = new Point2D.Double(Factor * cds[j][0] + Factor, Factor * cds[j][1] + Factor);
    }
    }//for loop end
    /*Path2D.Double*/ path = new Path2D.Double();
    System.out.println("1path bnds=" + path.getBounds());
    }
    The "cds" coordinates when given directly as values get plotted whereas when the formula to use the coordinates is used there are just two points getting plotted. Can you help me out with this????

    They are just mere formulas and need to be calculated over the range of datapts.

    More over i am putting a similar code which uses integer datatype.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
     
    public class CurveFit extends JPanel implements ActionListener {
        ButtonManager buttonManager;
        Point[] points;
        Path2D.Double path;
        Line2D.Double[] connectors;
        boolean showConnections = false;
        boolean removePoint = false;
        boolean firstTime = true;
     
        CurveFit() {
            int[][] cds = {
                { 150,400 }, {200,360 }, {250,320 }, {300,280},{350,150}
            };
            points = new Point[cds.length];
            for(int j = 0; j < cds.length; j++) {
                points[j] = new Point(cds[j][0], cds[j][1]);
            }
            path = new Path2D.Double();
        }
     
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("add")) {
                connectors = new Line2D.Double[points.length-1];
                showConnections = true;
                repaint();
            }
            if(ac.equals("cancel")) {
                showConnections = false;
                removePoint = false;
                repaint();
            }
            if(ac.equals("remove")) {
                removePoint = true;
            }
        }
     
        public void addPoint(Point p, int index) {
            int size = points.length;
            Point[] temp = new Point[size+1];
            System.arraycopy(points, 0, temp, 0, index);
            temp[index] = p;
            System.arraycopy(points, index, temp, index+1, size-index);
            points = temp;
            buttonManager.reset();
            showConnections = false;
            setPath();
            repaint();
        }
     
        public void removePoint(Point p) {
            int size = points.length;
            Point[] temp = new Point[size-1];
            for(int j = 0, k = 0; j < size; j++) {
                if(points[j] == p)
                    continue;
                temp[k++] = points[j];
            }
            points = temp;
            buttonManager.reset();
            removePoint = false;
            setPath();
            repaint();
        }
     
        public void setPoint(Point p, int x, int y) {
            p.setLocation(x, y);
            setPath();
            repaint();
        }
        
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
                                RenderingHints.VALUE_STROKE_PURE);
            if(firstTime) {
                firstTime = false;
                setPath();
            }
            g2.setPaint(Color.green.darker());
            g2.draw(path);
            g2.setPaint(Color.red);
            for(int j = 0; j < points.length; j++) {
                mark(g2, points[j]);
            }
            // For adding a point.
            if(showConnections) {
                g2.setPaint(Color.yellow);
                for(int j = 0; j < points.length-1; j++) {
                    connectors[j] = new Line2D.Double(points[j], points[j+1]);
                    g2.draw(connectors[j]);
                }
            }
        }
     
        /**
         *  P(t) = B(n,0)*P0 + B(n,1)*P1 + ... + B(n,n)*Pn
         *      0 <= t <= 1
         *
         *  B(n,m) = mth coefficient of nth degree Bernstein polynomial
         *         = C(n,m) * t^(m) * (1 - t)^(n-m)
         *  C(n,m) = Combinations of n things, taken m at a time
         *         = n! / (m! * (n-m)!)
         */
        private void setPath() {
            path.reset();
            int n = points.length;
            int w = getWidth();
            for(int j = 0; j <= w; j++) {
                double t = (double)j/w;          // [0 <= t <= 1.0]
                double x = 0;
                double y = 0;
                for(int k = 0; k < n; k++) {
                    x += B(n-1,k,t)*points[k].x;
                    y += B(n-1,k,t)*points[k].y;
                }
                if(j > 0)
                    path.lineTo(x,y);
                else
                    path.moveTo(x,y);
            }
        }
     
        private double B(int n, int m, double t) {
            return C(n,m) * Math.pow(t, m) * Math.pow(1.0 - t, n-m);
        }
     
        private double C(int n, int m) {
            return factorial(n) / (factorial(m)*factorial(n-m));
        }
     
        private int factorial(int n) {
            return (n > 1) ? n*factorial(n-1) : 1;
        }
     
        private void mark(Graphics2D g2, Point p) {
            g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
        }
     
        private JPanel getButtonPanel() {
            buttonManager = new ButtonManager();
            String[] ids = { "add", "cancel", "remove" };
            JPanel panel = new JPanel();
            for(int j = 0; j < ids.length; j++) {
                JButton button = new JButton(ids[j]);
                button.setEnabled(j != 1);
                buttonManager.add(button);
                button.setActionCommand(ids[j]);
                button.addActionListener(this);
                panel.add(button);
            }
            return panel;
        }
     
        public static void main(String[] args) {
            CurveFit test = new CurveFit();
            PointMover mover = new PointMover(test);
            test.addMouseListener(mover);
            test.addMouseMotionListener(mover);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.add(test.getButtonPanel(), "Last");
            f.setSize(500,500);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
     
    class PointMover extends MouseInputAdapter {
        CurveFit component;
        Point selectedPoint;
        Cursor cursor;
        Cursor defaultCursor = Cursor.getDefaultCursor();
        Point offset = new Point();
        boolean dragging = false;
        final int PROX_DIST = 5;
     
        PointMover(CurveFit cf) {
            component = cf;
            BufferedImage image = getImage();
            Point hotspot = new Point(17,17);
            cursor = Toolkit.getDefaultToolkit()
                            .createCustomCursor(image, hotspot, null);
        }
     
        public void mousePressed(MouseEvent e) {
            if(selectedPoint != null) {
                if(component.removePoint) {                // remove
                    component.removePoint(selectedPoint);
                } else {                                   // drag
                    offset.x = e.getX() - selectedPoint.x;
                    offset.y = e.getY() - selectedPoint.y;
                    dragging = true;
                }
            } else if(component.showConnections) {         // add
                Point p = e.getPoint();
                Line2D.Double[] lines = component.connectors;
                for(int j = 0; j < lines.length; j++) {
                    if(lines[j].ptSegDist(p) < PROX_DIST) {
                        component.addPoint(p, j+1);
                        break;
                    }
                }
            }
        }
     
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        }
     
        public void mouseDragged(MouseEvent e) {
            if(dragging) {
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                component.setPoint(selectedPoint, x, y);
            }
        }
     
        /** For point selection. */
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            Point[] pts = component.points;
            boolean hovering = false;
            for(int j = 0; j < pts.length; j++) {
                if(pts[j].distance(p) < PROX_DIST) {
                    hovering = true;
                    if(selectedPoint != pts[j]) {
                        selectedPoint = pts[j];
                        component.setCursor(cursor);
                        break;
                    }
                }
            }
     
            if(!hovering && selectedPoint != null) {
                selectedPoint = null;
                component.setCursor(defaultCursor);
            }
        }
     
        private BufferedImage getImage() {
            int w = 27, h = 27,
                type = BufferedImage.TYPE_INT_ARGB_PRE;
            BufferedImage image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(new Color(0x333333));
            g2.draw(new Line2D.Double(w/2, 0, w/2, 8));    // n
            g2.draw(new Line2D.Double(0, h/2, 8, h/2));    // w
            g2.draw(new Line2D.Double(w/2, h-8, w/2, h));  // s
            g2.draw(new Line2D.Double(w-8, h/2, w, h/2));  // e
            g2.dispose();
            return image;
        }
    }
     
    class ButtonManager implements ActionListener {
        JButton[] buttons = new JButton[0];
     
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("add")) {
                getButton("remove").setEnabled(false);
                enable(true);
            } else if(ac.equals("remove")) {
                getButton("add").setEnabled(false);
                enable(true);
            } else {
     
                reset();
            }
        }
     
        public void reset() {
            getButton("add").setEnabled(true);
            getButton("remove").setEnabled(true);
            enable(false);
        }
     
        private void enable(boolean enable) {
            getButton("cancel").setEnabled(enable);
        }
     
        public void add(JButton button) {
            button.addActionListener(this);
            int size = buttons.length;
            JButton[] temp = new JButton[size+1];
            System.arraycopy(buttons, 0, temp, 0, size);
            temp[size] = button;
            buttons = temp;
        }
     
        private JButton getButton(String target) {
            for(int j = 0; j < buttons.length; j++) {
                if(buttons[j].getActionCommand().equals(target))
                    return buttons[j];
            }
            return null;
        }
    }
    please do run this code and try to move the points (Control points) the shape remains a curve. I have tried to use the same logic but when i move the points in Double datatype code they move as line????? can some one help me out with this????
    Please some one help me out with this?????????????

    for ref i am posting the url of the other forum i have put the topic
    <<http://forums.devshed.com/java-help-9/java-awt-746288-2.html#post2535792>>
    Both the threads in the site


    thanks in advance
    Last edited by murdplacid; 09-22-2010 at 04:43 AM.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

  6. #6
    murdplacid is offline Member
    Join Date
    Sep 2010
    Posts
    9
    Rep Power
    0

    Default

    This is the code i have edited many parts of it and now i have no errors in it.But now i have problem the curve which is drawn does not pass through all the points in the graph.
    Can some one help me out with this?????
    Thanks in advance..

    [CODE]
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;


    public class DrawCurve extends JPanel implements ActionListener {
    ButtonManager buttonManager;
    Path2D.Double path;
    Point2D.Double[] points;
    Line2D.Double[] connectors;
    boolean showConnections= false;
    boolean removePoint= false;
    boolean firstTime= true;
    final double Factor = 500.0D;


    DrawCurve() {


    double[][] cds={{0.00000, 0.00000},
    {-0.00032, 0.00838},
    {0.00378, 0.01779},
    {0.01233, 0.02815},
    {0.04285, 0.05108},
    {0.06478, 0.06320},
    {0.09110, 0.07539},
    {0.12172, 0.08733},
    {0.15651, 0.09868},
    {0.19533, 0.10908},
    {0.23796, 0.11819},
    {0.28417, 0.12564},
    {0.33371, 0.13113},
    {0.38625, 0.13435},
    {0.44148, 0.13502},
    {0.49906, 0.13293},
    {0.55862, 0.12788},
    {0.61979, 0.11971},
    {0.68221, 0.10832},
    {0.74551, 0.09361},
    {0.80933, 0.07555},
    {0.87332, 0.05412},
    {0.93711, 0.02932},
    {1.00036, 0.00121},
    {0.00460, -0.00701},
    {0.01333, -0.01236},
    {0.02610, -0.01609},
    {0.04279, -0.01825},
    {0.06329, -0.01891},
    {0.08746, -0.01819},
    {0.11515, -0.01620},
    {0.14623, -0.01308},
    {0.18055, -0.00900},
    {0.21797, -0.00416},
    {0.25836, 0.00122},
    {0.30161, 0.00690},
    {0.34760, 0.01262},
    {0.39623, 0.01808},
    {0.44738, 0.02300},
    {0.50094, 0.02707},
    {0.55681, 0.02999},
    {0.61485, 0.03148},
    {0.67491, 0.03128},
    {0.73685, 0.02916},
    {0.80049, 0.02495},
    {0.86563, 0.01851},
    {0.93208, 0.00980},
    {0.99964, -0.00121}

    };

    points = new Point2D.Double[cds.length];

    for(int j = 0; j < cds.length; j++) { // NOTE 1 based? -1 stops short here also
    points[j] = new Point2D.Double(Factor * cds[j][0] + Factor, Factor * cds[j][1] + Factor);
    }
    /*Path2D.Double*/ path = new Path2D.Double();
    //System.out.println("1path bnds=" + path.getBounds());
    }



    public void actionPerformed(ActionEvent e) {
    //System.out.println("aP e=" + e);
    String ac = e.getActionCommand();
    if(ac.equals("add")) {
    connectors = new Line2D.Double[points.length-1];
    showConnections = true;
    repaint();
    }
    if(ac.equals("cancel")) {
    showConnections = false;
    removePoint = false;
    repaint();
    }
    if(ac.equals("remove")) {
    removePoint = true;
    }
    }

    public void addPoint(Point2D.Double p, int index) {
    int size = points.length;
    Point2D.Double[] temp = new Point2D.Double[size+1];
    System.arraycopy(points, 0, temp, 0, index);
    temp[index] = p;
    System.arraycopy(points, index, temp, index+1, size-index);
    points = temp;
    buttonManager.reset();
    showConnections = false;
    setPath();
    repaint();
    }

    public void removePoint(Point2D.Double p) {
    int size = points.length;
    Point2D.Double[] temp = new Point2D.Double[size-1];
    for(int j = 0, k = 0; j < size; j++) {
    if(points[j] == p)
    continue;
    temp[k++] = points[j];
    }
    points = temp;
    buttonManager.reset();
    removePoint = false;
    setPath();
    repaint();
    }

    public void setPoint(Point2D.Double p,double x,double y) {
    p.setLocation(x, y);
    setPath();
    repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    //System.out.println("pC path bnds=" + path.getBounds()); //pC path //bnds=java.awt.Rectangle[x=0,y=0,width=0,height=0]
    Graphics2D g2 = (Graphics2D)g;
    //Path2D.Double path = new Path2D.Double();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONT ROL,
    RenderingHints.VALUE_STROKE_PURE);
    if(firstTime) {
    firstTime = false;
    setPath();
    }
    g2.setPaint(Color.green.darker());

    g2.draw(path); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ????

    g2.setPaint(Color.red);
    for(int j = 0; j < points.length; j++) {
    mark(g2, points[j]);
    }
    // For adding a point.
    if(showConnections) {
    g2.setPaint(Color.yellow);
    for(int j = 0; j < points.length-1; j++) {
    connectors[j] = new Line2D.Double(points[j], points[j+1]);
    g2.draw(connectors[j]);
    }
    }
    } // end paintComponent()

    /**
    * P(t) = B(n,0)*P0 + B(n,1)*P1 + ... + B(n,n)*Pn
    * 0 <= t <= 1
    *
    * B(n,m) = mth coefficient of nth degree Bernstein polynomial
    * = C(n,m) * t^(m) * (1 - t)^(n-m)
    * C(n,m) = Combinations of n things, taken m at a time
    * = n! / (m! * (n-m)!)
    */
    private void setPath() {
    //System.out.println("2path bnds=" + path.getBounds());
    path.reset();
    int n = points.length;
    int w = getWidth();
    for(int j = 0; j <= w; j++) {
    double t = (double)j/w; // [0 <= t <= 1.0]
    double x = 0;
    double y = 0;
    for(int k = 1; k < n; k++) {
    // System.out.println("k=" + k + " points[k]=" + points[k]); //k=0 points[k]=null
    x += B(n-1,k,t)*points[k].x;
    y += B(n-1,k,t)*points[k].y;
    }
    if(j > 0)
    path.lineTo(x,y);
    else
    path.moveTo(x,y);
    }
    } // end setPath()

    private double B(int n, int m, double t) {
    return C(n,m) * Math.pow(t, m) * Math.pow(1.0 - t, n-m);
    }

    private double C(int n, int m) {
    return factorial(n) / (factorial(m)*factorial(n-m));
    }

    private double factorial(int n) {
    return (n > 1) ? n*factorial(n-1) : 1;
    }

    private void mark(Graphics2D g2, Point2D.Double p) {
    g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
    }

    private JPanel getButtonPanel() {
    buttonManager = new ButtonManager();
    String[] ids = { "add", "cancel", "remove" };
    JPanel panel = new JPanel();
    for(int j = 0; j < ids.length; j++) {
    JButton button = new JButton(ids[j]);
    button.setEnabled(j != 1);
    buttonManager.add(button);
    button.setActionCommand(ids[j]);
    button.addActionListener(this);
    panel.add(button);
    }
    return panel;
    }
    //----------------------------------------------------------------
    public static void main(String[] args) {
    DrawCurve test = new DrawCurve();
    PointMover mover = new PointMover(test);
    test.addMouseListener(mover);
    test.addMouseMotionListener(mover);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(test);
    f.add(test.getButtonPanel(), "Last");
    f.setSize(1200,800);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }
    }
    //-------------------------------------------------------
    class PointMover extends MouseInputAdapter {
    DrawCurve component;
    Point2D.Double selectedPoint;
    Cursor cursor;
    Cursor defaultCursor = Cursor.getDefaultCursor();
    Point2D.Double offset = new Point2D.Double();
    boolean dragging = false;
    final int PROX_DIST = 5;

    PointMover(DrawCurve cf) {
    component = cf;
    BufferedImage image = getImage();
    Point hotspot = new Point(17,17);
    cursor = Toolkit.getDefaultToolkit().createCustomCursor(ima ge, hotspot, null);
    }

    public void mousePressed(MouseEvent e) {
    if(selectedPoint != null) {
    if(component.removePoint) { // remove
    component.removePoint(selectedPoint);
    } else { // drag
    offset.x = e.getX() - selectedPoint.x;
    offset.y = e.getY() - selectedPoint.y;
    dragging = true;
    }
    } else if(component.showConnections) { // add
    Point p = e.getPoint();
    Line2D.Double[] lines = component.connectors;
    for(int j = 0; j < lines.length; j++) {
    if(lines[j].ptSegDist(p) < PROX_DIST) {
    //component.addPoint(p, j+1);
    break;
    }
    }
    }
    }

    public void mouseReleased(MouseEvent e) {
    dragging = false;
    }

    public void mouseDragged(MouseEvent e) {
    if(dragging) {
    double x = e.getX() - offset.x;
    double y = e.getY() - offset.y;
    component.setPoint(selectedPoint, x, y);
    }
    }

    /** For point selection. */
    public void mouseMoved(MouseEvent e) {
    Point p = e.getPoint();
    Point2D.Double[] pts = component.points;
    boolean hovering = false;
    for(int j = 0; j < pts.length; j++) {
    if(pts[j].distance(p) < PROX_DIST) {
    hovering = true;
    if(selectedPoint != pts[j]) {
    selectedPoint = pts[j];
    component.setCursor(cursor);
    break;
    }
    }
    }

    if(!hovering && selectedPoint != null) {
    selectedPoint = null;
    component.setCursor(defaultCursor);
    }
    }

    private BufferedImage getImage() {
    int w = 27, h = 27,
    type = BufferedImage.TYPE_INT_ARGB_PRE;
    BufferedImage image = new BufferedImage(w, h, type);
    Graphics2D g2 = image.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(new Color(0x333333));
    g2.draw(new Line2D.Double(w/2, 0, w/2, 8)); // n
    g2.draw(new Line2D.Double(0, h/2, 8, h/2)); // w
    g2.draw(new Line2D.Double(w/2, h-8, w/2, h)); // s
    g2.draw(new Line2D.Double(w-8, h/2, w, h/2)); // e
    g2.dispose();
    return image;
    }
    }

    //----------------------------------------
    class ButtonManager implements ActionListener {
    JButton[] buttons = new JButton[0];

    public void actionPerformed(ActionEvent e) {
    String ac = e.getActionCommand();
    if(ac.equals("add")) {
    getButton("remove").setEnabled(false);
    enable(true);

    } else if(ac.equals("remove")) {
    getButton("add").setEnabled(false);
    enable(true);
    } else {

    reset();
    }
    }

    public void reset() {
    getButton("add").setEnabled(true);
    getButton("remove").setEnabled(true);
    enable(false);
    }

    private void enable(boolean enable) {
    getButton("cancel").setEnabled(enable);
    }

    public void add(JButton button) {
    button.addActionListener(this);
    int size = buttons.length;
    JButton[] temp = new JButton[size+1];
    System.arraycopy(buttons, 0, temp, 0, size);
    temp[size] = button;
    buttons = temp;
    }

    private JButton getButton(String target) {
    for(int j = 0; j < buttons.length; j++) {
    if(buttons[j].getActionCommand().equals(target))
    return buttons[j];
    }
    return null;
    }

    } // end class
    []/CODE

  7. #7
    murdplacid is offline Member
    Join Date
    Sep 2010
    Posts
    9
    Rep Power
    0

    Default Change in the code

    This is the code i have edited many parts of it and now i have no errors in it.But now i have problem the curve which is drawn does not pass through all the points in the graph.
    Can some one help me out with this?????
    Thanks in advance.. More over the statement
    //component.addPoint(p, j+1);
    in the point mover class. can that be the issue????????

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    
    
    public class DrawCurve extends JPanel implements ActionListener {
    	ButtonManager buttonManager;
    	Path2D.Double path;
    	Point2D.Double[] points;
    	Line2D.Double[] connectors;
    	boolean showConnections= false;
    	boolean removePoint= false;
    	boolean firstTime= true;
    	final double Factor = 500.0D;
    
    
    	DrawCurve() {
    
    
    	double[][] cds={{0.00000,	0.00000},
    {-0.00032,	0.00838},
    {0.00378,	0.01779},
    {0.01233,	0.02815},
    {0.04285,	0.05108},
    {0.06478,	0.06320},
    {0.09110,	0.07539},
    {0.12172,	0.08733},
    {0.15651,	0.09868},
    {0.19533,	0.10908},
    {0.23796,	0.11819},
    {0.28417,	0.12564},
    {0.33371,	0.13113},
    {0.38625,	0.13435},
    {0.44148,	0.13502},
    {0.49906,	0.13293},
    {0.55862,	0.12788},
    {0.61979,	0.11971},
    {0.68221,	0.10832},
    {0.74551,	0.09361},
    {0.80933,	0.07555},
    {0.87332,	0.05412},
    {0.93711,	0.02932},
    {1.00036,	0.00121},
    {0.00460,	-0.00701},
    {0.01333,	-0.01236},
    {0.02610,	-0.01609},
    {0.04279,	-0.01825},
    {0.06329,	-0.01891},
    {0.08746,	-0.01819},
    {0.11515,	-0.01620},
    {0.14623,	-0.01308},
    {0.18055,	-0.00900},
    {0.21797,	-0.00416},
    {0.25836,	0.00122},
    {0.30161,	0.00690},
    {0.34760,	0.01262},
    {0.39623,	0.01808},
    {0.44738,	0.02300},
    {0.50094,	0.02707},
    {0.55681,	0.02999},
    {0.61485,	0.03148},
    {0.67491,	0.03128},
    {0.73685,	0.02916},
    {0.80049,	0.02495},
    {0.86563,	0.01851},
    {0.93208,	0.00980},
    {0.99964,	-0.00121}
    
    };
    
    	points = new Point2D.Double[cds.length];
    
    	for(int j = 0; j < cds.length; j++) { // NOTE 1 based? -1 stops short here also
    		points[j] = new Point2D.Double(Factor * cds[j][0] + Factor, Factor * cds[j][1] + Factor);
    	}
    /*Path2D.Double*/ path = new Path2D.Double();
    	//System.out.println("1path bnds=" + path.getBounds());
    	}
    
    
    
    public void actionPerformed(ActionEvent e) {
    	//System.out.println("aP e=" + e);
    	String ac = e.getActionCommand();
    	if(ac.equals("add")) {
    	connectors = new Line2D.Double[points.length-1];
    	showConnections = true;
    	repaint();
    	}
    	if(ac.equals("cancel")) {
    	showConnections = false;
    	removePoint = false;
    	repaint();
    	}
    	if(ac.equals("remove")) {
    	removePoint = true;
    	}
    }
    
    public void addPoint(Point2D.Double p, int index) {
    	int size = points.length;
    	Point2D.Double[] temp = new Point2D.Double[size+1];
    	System.arraycopy(points, 0, temp, 0, index);
    	temp[index] = p;
    	System.arraycopy(points, index, temp, index+1, size-index);
    	points = temp;
    	buttonManager.reset();
    	showConnections = false;
    	setPath();
    	repaint();
    }
    
    public void removePoint(Point2D.Double p) {
    	int size = points.length;
    	Point2D.Double[] temp = new Point2D.Double[size-1];
    	for(int j = 0, k = 0; j < size; j++) {
    		if(points[j] == p)
    			continue;
    		temp[k++] = points[j];
    	}
    	points = temp;
    	buttonManager.reset();
    	removePoint = false;
    	setPath();
    	repaint();
    }
    
    public void setPoint(Point2D.Double p,double x,double y) {
    	p.setLocation(x, y);
    	setPath();
    	repaint();
    }
    
    @Override
    protected void paintComponent(Graphics g) {
    	super.paintComponent(g);
    	//System.out.println("pC path bnds=" + path.getBounds()); //pC path //bnds=java.awt.Rectangle[x=0,y=0,width=0,height=0]
    	Graphics2D g2 = (Graphics2D)g;
    	//Path2D.Double path = new Path2D.Double();
    	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    			RenderingHints.VALUE_ANTIALIAS_ON);
    	g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
    			RenderingHints.VALUE_STROKE_PURE);
    	if(firstTime) {
    	firstTime = false;
    	setPath();
    	}
    	g2.setPaint(Color.green.darker());
    
    	g2.draw(path); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ????
    
    	g2.setPaint(Color.red);
    	for(int j = 0; j < points.length; j++) {
    	mark(g2, points[j]);
    	}
    // For adding a point.
    	if(showConnections) {
    	g2.setPaint(Color.yellow);
    	for(int j = 0; j < points.length-1; j++) {
    	connectors[j] = new Line2D.Double(points[j], points[j+1]);
    	g2.draw(connectors[j]);
    	}
        }
    } // end paintComponent()
    
    /**
    * P(t) = B(n,0)*P0 + B(n,1)*P1 + ... + B(n,n)*Pn
    * 0 <= t <= 1
    *
    * B(n,m) = mth coefficient of nth degree Bernstein polynomial
    * = C(n,m) * t^(m) * (1 - t)^(n-m)
    * C(n,m) = Combinations of n things, taken m at a time
    * = n! / (m! * (n-m)!)
    */
    private void setPath() {
    	//System.out.println("2path bnds=" + path.getBounds());
    	path.reset();
    	int n = points.length;
    	int w = getWidth();
    	for(int j = 0; j <= w; j++) {
    	double t = (double)j/w; // [0 <= t <= 1.0]
    	double x = 0;
    	double y = 0;
    	for(int k = 1; k < n; k++) {
    	// System.out.println("k=" + k + " points[k]=" + points[k]); //k=0 points[k]=null
    	x += B(n-1,k,t)*points[k].x;
    	y += B(n-1,k,t)*points[k].y;
    	}
    	if(j > 0)
    		path.lineTo(x,y);
    	else
    		path.moveTo(x,y);
    	}
    } // end setPath()
    
    private double B(int n, int m, double t) {
    	return C(n,m) * Math.pow(t, m) * Math.pow(1.0 - t, n-m);
    }
    
    private double C(int n, int m) {
    	return factorial(n) / (factorial(m)*factorial(n-m));
    }
    
    private double factorial(int n) {
    	return (n > 1) ? n*factorial(n-1) : 1;
    }
    
    private void mark(Graphics2D g2, Point2D.Double p) {
    	g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
    }
    
    private JPanel getButtonPanel() {
    	buttonManager = new ButtonManager();
    	String[] ids = { "add", "cancel", "remove" };
    	JPanel panel = new JPanel();
    	for(int j = 0; j < ids.length; j++) {
    		JButton button = new JButton(ids[j]);
    		button.setEnabled(j != 1);
    		buttonManager.add(button);
    		button.setActionCommand(ids[j]);
    		button.addActionListener(this);
    		panel.add(button);
    	}
    	return panel;
    }
    //----------------------------------------------------------------
    public static void main(String[] args) {
    	DrawCurve test = new DrawCurve();
    	PointMover mover = new PointMover(test);
    	test.addMouseListener(mover);
    	test.addMouseMotionListener(mover);
    	JFrame f = new JFrame();
    	f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	f.add(test);
    	f.add(test.getButtonPanel(), "Last");
    	f.setSize(1200,800);
    	f.setLocationRelativeTo(null);
    	f.setVisible(true);
    	}
    }
    //-------------------------------------------------------
    class PointMover extends MouseInputAdapter {
    	DrawCurve component;
    	Point2D.Double selectedPoint;
    	Cursor cursor;
    	Cursor defaultCursor = Cursor.getDefaultCursor();
    	Point2D.Double offset = new Point2D.Double();
    	boolean dragging = false;
    	final int PROX_DIST = 5;
    
    	PointMover(DrawCurve cf) {
    		component = cf;
    		BufferedImage image = getImage();
    		Point hotspot = new Point(17,17);
    		cursor = Toolkit.getDefaultToolkit().createCustomCursor(image, hotspot, null);
    	}	
    
    	public void mousePressed(MouseEvent e) {
    		if(selectedPoint != null) {
    			if(component.removePoint) { // remove
    				component.removePoint(selectedPoint);
    			} else { // drag
    				offset.x = e.getX() - selectedPoint.x;
    				offset.y = e.getY() - selectedPoint.y;
    				dragging = true;
    				}
    		} else if(component.showConnections) { // add
    			Point p = e.getPoint();
    			Line2D.Double[] lines = component.connectors;
    			for(int j = 0; j < lines.length; j++) {
    				if(lines[j].ptSegDist(p) < PROX_DIST) {
    				//component.addPoint(p, j+1);
    				break;
    				}
    			}
    		}
    	}
    
    	public void mouseReleased(MouseEvent e) {
    		dragging = false;
    	}
    
    	public void mouseDragged(MouseEvent e) {
    		if(dragging) {
    			double x = e.getX() - offset.x;
    			double y = e.getY() - offset.y;
    			component.setPoint(selectedPoint, x, y);
    		}
    	}	
    
    /** For point selection. */
    	public void mouseMoved(MouseEvent e) {
    		Point p = e.getPoint();
    		Point2D.Double[] pts = component.points;
    		boolean hovering = false;
    		for(int j = 0; j < pts.length; j++) {
    			if(pts[j].distance(p) < PROX_DIST) {
    				hovering = true;	
    				if(selectedPoint != pts[j]) {
    					selectedPoint = pts[j];
    					component.setCursor(cursor);
    					break;
    				}
    			}
    		}
    
    	if(!hovering && selectedPoint != null) {
    		selectedPoint = null;
    		component.setCursor(defaultCursor);
    		}
    	}
    
    	private BufferedImage getImage() {
    		int w = 27, h = 27,
    		type = BufferedImage.TYPE_INT_ARGB_PRE;
    		BufferedImage image = new BufferedImage(w, h, type);
    		Graphics2D g2 = image.createGraphics();
    		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    			RenderingHints.VALUE_ANTIALIAS_ON);
    		g2.setPaint(new Color(0x333333));
    		g2.draw(new Line2D.Double(w/2, 0, w/2, 8)); // n
    		g2.draw(new Line2D.Double(0, h/2, 8, h/2)); // w
    		g2.draw(new Line2D.Double(w/2, h-8, w/2, h)); // s
    		g2.draw(new Line2D.Double(w-8, h/2, w, h/2)); // e
    		g2.dispose();
    		return image;
    	}
    }
    
    //----------------------------------------
    class ButtonManager implements ActionListener {
    	JButton[] buttons = new JButton[0];
    
    	public void actionPerformed(ActionEvent e) {
    		String ac = e.getActionCommand();
    			if(ac.equals("add")) {
    			getButton("remove").setEnabled(false);
    			enable(true);
    		
    			} else if(ac.equals("remove")) {
    				getButton("add").setEnabled(false);
    				enable(true);
    				} else {
    
    					reset();
    					}
    				}
    	
    	public void reset() {
    		getButton("add").setEnabled(true);
    		getButton("remove").setEnabled(true);
    		enable(false);
    	}
    
    	private void enable(boolean enable) {
    		getButton("cancel").setEnabled(enable);
    	}
    
    	public void add(JButton button) {
    		button.addActionListener(this);
    		int size = buttons.length;
    		JButton[] temp = new JButton[size+1];
    		System.arraycopy(buttons, 0, temp, 0, size);
    		temp[size] = button;
    		buttons = temp;
    	}
    
    	private JButton getButton(String target) {
    		for(int j = 0; j < buttons.length; j++) {
    		if(buttons[j].getActionCommand().equals(target))
    		return buttons[j];
    	}
    	return null;
    	}
    
    } // end class

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    Add some debugging code to the program to show the points it is using to draw the green line. For example add this to setPath and look at the x,y points.

    System.out.println("j=" + j + " x=" + x + ", y=" + y); // show points on path

    How is that path related to the red dots that are plotted?
    Last edited by Norm; 09-22-2010 at 05:04 PM.

  9. #9
    murdplacid is offline Member
    Join Date
    Sep 2010
    Posts
    9
    Rep Power
    0

    Default can u help me out with this??

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    
    
    public class DrawCurve extends JPanel implements ActionListener {
    	ButtonManager buttonManager;
    	Path2D.Double path;
    	Point2D.Double[] points;
    	Line2D.Double[] connectors;
    	boolean showConnections= false;
    	boolean removePoint= false;
    	boolean firstTime= true;
    	final double Factor = 500.0D;
    
    
    	DrawCurve() {
    
    
    	double[][] cds={{1.00036,	0.00121},{0.93711,	0.02932},{0.87332,	0.05412},{0.80933,	
    
    0.07555},{0.74551,	0.09361},{0.68221,	0.10832},{0.61979,	0.11971},{0.55862,	
    
    0.12788},{0.49906,	0.13293},{0.44148,	0.13502},{0.38625,	0.13435},{0.33371,	
    
    0.13113},{0.28417,	0.12564},{0.23796,	0.11819},{0.19533,	0.10908},{0.15651,	
    
    0.09868},{0.12172,	0.08733},{0.09110,	0.07539},{0.06478,	0.06320},{0.04285,	
    
    0.05108},{0.01233,	0.02815},{0.00378,	0.01779},{-0.00032,	0.00838},{0.00000,	
    
    0.00000},{0.00000,         0.0000},{0.00460,	-0.00701},{0.01333,	-0.01236},{0.02610,	
    
    -0.01609},{0.04279,	-0.01825},{0.06329,	-0.01891},{0.08746,	-0.01819},{0.11515,	
    
    -0.01620},{0.14623,	-0.01308},{0.18055,	-0.00900},{0.21797,	-0.00416},{0.25836,	
    
    0.00122},{0.30161,	0.00690},{0.34760,	0.01262},{0.39623,	0.01808},{0.44738,	
    
    0.02300},{0.50094,	0.02707},{0.55681,	0.02999},{0.61485,	0.03148},{0.67491,	
    
    0.03128},{0.73685,	0.02916},{0.86563,	0.01851},{0.86563,	0.01851},{0.93208,	0.00980},
    {0.99964,	-0.00121}
    
    
    
    };
    
    	points = new Point2D.Double[cds.length];
    
    	for(int j = 0; j < cds.length; j++) { // NOTE 1 based? -1 stops short here also
    		points[j] = new Point2D.Double(Factor * cds[j][0] + Factor, Factor * cds[j][1] + Factor);
    	}
    /*Path2D.Double*/ path = new Path2D.Double();
    	//System.out.println("1path bnds=" + path.getBounds());
    	}
    
    
    //----------------------------------------------------------------
    public void actionPerformed(ActionEvent e) {
    	//System.out.println("aP e=" + e);
    	String ac = e.getActionCommand();
    	if(ac.equals("add")) {
    	connectors = new Line2D.Double[points.length-1];
    	showConnections = true;
    	repaint();
    	}
    	if(ac.equals("cancel")) {
    	showConnections = false;
    	removePoint = false;
    	repaint();
    	}
    	if(ac.equals("remove")) {
    	removePoint = true;
    	}
    }
    //--------------------------------------------------------------------
    public void addPoint(Point2D.Double p, int index) {
    	int size = points.length;
    	Point2D.Double[] temp = new Point2D.Double[size+1];
    	System.arraycopy(points, 0, temp, 0, index);
    	temp[index] = p;
    	System.arraycopy(points, index, temp, index+1, size-index);
    	points = temp;
    	buttonManager.reset();
    	showConnections = false;
    	setPath();
    	repaint();
    }
    //---------------------------------------------------------------------
    public void removePoint(Point2D.Double p) {
    	int size = points.length;
    	Point2D.Double[] temp = new Point2D.Double[size-1];
    	for(int j = 0, k = 0; j < size; j++) {
    		if(points[j] == p)
    			continue;
    		temp[k++] = points[j];
    	}
    	points = temp;
    	buttonManager.reset();
    	removePoint = false;
    	setPath();
    	repaint();
    }
    //------------------------------------------------------------------------
    public void setPoint(Point2D.Double p,double x,double y) {
    	p.setLocation(x, y);
    	setPath();
    	repaint();
    }
    //---------------------------------------------------------------------------
    @Override
    protected void paintComponent(Graphics g) {
    	super.paintComponent(g);
    	//System.out.println("pC path bnds=" + path.getBounds()); //pC path 
    
    //bnds=java.awt.Rectangle[x=0,y=0,width=0,height=0]
    	Graphics2D g2 = (Graphics2D)g;
    	//Path2D.Double path = new Path2D.Double();
    	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    			RenderingHints.VALUE_ANTIALIAS_ON);
    	g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
    			RenderingHints.VALUE_STROKE_PURE);
    	if(firstTime) {
    	firstTime = false;
    	setPath();
    	}
    	g2.setPaint(Color.green.darker());
    
    	g2.draw(path); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ????
    
    	g2.setPaint(Color.red);
    	for(int j = 0; j < points.length; j++) {
    	mark(g2, points[j]);
    	}
    // For adding a point.
    	if(showConnections) {
    	g2.setPaint(Color.yellow);
    	for(int j = 0; j < points.length-1; j++) {
    	connectors[j] = new Line2D.Double(points[j], points[j+1]);
    	g2.draw(connectors[j]);
    	}
        }
    } // end paintComponent()
    
    /**
    * P(t) = B(n,0)*P0 + B(n,1)*P1 + ... + B(n,n)*Pn
    * 0 <= t <= 1
    *
    * B(n,m) = mth coefficient of nth degree Bernstein polynomial
    * = C(n,m) * t^(m) * (1 - t)^(n-m)
    * C(n,m) = Combinations of n things, taken m at a time
    * = n! / (m! * (n-m)!)
    */
    private void setPath() {
    	//System.out.println("2path bnds=" + path.getBounds());
    	path.reset();
    	int n = points.length;
    	int w = getWidth();
    	for(int j = 0; j <= w; j++) {
    	double t = (double)j/w; // [0 <= t <= 1.0]
    	double x = 0;
    	double y = 0;
    	for(int k = 1; k < n; k++) {
    	//System.out.println("k=" + k + " points[k]=" + points[k]); //k=0 points[k]=null
    	x += B(n-1,k,t)*points[k].x;
    	y += B(n-1,k,t)*points[k].y;
    	//System.out.println("j=" + j + " x=" + x + ", y=" + y);
    	}
    	if(j > 0)
    		path.lineTo(x,y);
    	else
    		path.moveTo(x,y);
    	}
    	
    } // end setPath()
    
    private double B(int n, int m, double t) {
    	return C(n,m) * Math.pow(t, m) * Math.pow(1.0 - t, n-m);
    }
    
    private double C(int n, int m) {
    	return factorial(n) / (factorial(m)*factorial(n-m));
    }
    
    private double factorial(int n) {
    	return (n > 1) ? n*factorial(n-1) : 1;
    }
    
    private void mark(Graphics2D g2, Point2D.Double p) {
    	g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
    }
    
    private JPanel getButtonPanel() {
    	buttonManager = new ButtonManager();
    	String[] ids = { "add", "cancel", "remove" };
    	JPanel panel = new JPanel();
    	for(int j = 0; j < ids.length; j++) {
    		JButton button = new JButton(ids[j]);
    		button.setEnabled(j != 1);
    		buttonManager.add(button);
    		button.setActionCommand(ids[j]);
    		button.addActionListener(this);
    		panel.add(button);
    	}
    	return panel;
    }
    //----------------------------------------------------------------
    public static void main(String[] args) {
    	DrawCurve test = new DrawCurve();
    	PointMover mover = new PointMover(test);
    	test.addMouseListener(mover);
    	test.addMouseMotionListener(mover);
    	JFrame f = new JFrame();
    	f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	f.add(test);
    	f.add(test.getButtonPanel(), "Last");
    	f.setSize(1200,800);
    	f.setLocation(200,200);
    	f.setVisible(true);
    	}
    }
    //-------------------------------------------------------
    class PointMover extends MouseInputAdapter {
    	DrawCurve component;
    	Point2D.Double selectedPoint;
    	Cursor cursor;
    	Cursor defaultCursor = Cursor.getDefaultCursor();
    	Point2D.Double offset = new Point2D.Double();
    	boolean dragging = false;
    	final int PROX_DIST = 500;
    
    	PointMover(DrawCurve cf) {
    		component = cf;
    		BufferedImage image = getImage();
    		Point hotspot = new Point(17,17);
    		cursor = Toolkit.getDefaultToolkit().createCustomCursor(image, hotspot, null);
    	}	
    
    	public void mousePressed(MouseEvent e) {
    		if(selectedPoint != null) {
    			if(component.removePoint) { // remove
    				component.removePoint(selectedPoint);
    			} else { // drag
    				offset.x = e.getX() - selectedPoint.x;
    				offset.y = e.getY() - selectedPoint.y;
    				dragging = true;
    				}
    		} else if(component.showConnections) { // add
    			Point p = e.getPoint();
    			Line2D.Double[] lines = component.connectors;
    			for(int j = 0; j < lines.length; j++) {
    				if(lines[j].ptSegDist(p) < PROX_DIST) {
    				component.addPoint(p, j+1);
    				break;
    				}
    			}
    		}
    	}
    
    	public void mouseReleased(MouseEvent e) {
    		dragging = false;
    	}
    
    	public void mouseDragged(MouseEvent e) {
    		if(dragging) {
    			double x = e.getX() - offset.x;
    			double y = e.getY() - offset.y;
    			component.setPoint(selectedPoint, x, y);
    		}
    	}	
    
    /** For point selection. */
    	public void mouseMoved(MouseEvent e) {
    		Point p = e.getPoint();
    		Point2D.Double[] pts = component.points;
    		boolean hovering = false;
    		for(int j = 0; j < pts.length; j++) {
    			if(pts[j].distance(p) < PROX_DIST) {
    				hovering = true;	
    				if(selectedPoint != pts[j]) {
    					selectedPoint = pts[j];
    					component.setCursor(cursor);
    					break;
    				}
    			}
    		}
    
    	if(!hovering && selectedPoint != null) {
    		selectedPoint = null;
    		component.setCursor(defaultCursor);
    		}
    	}
    
    	private BufferedImage getImage() {
    		int w = 27, h = 27,
    		type = BufferedImage.TYPE_INT_ARGB_PRE;
    		BufferedImage image = new BufferedImage(w, h, type);
    		Graphics2D g2 = image.createGraphics();
    		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    			RenderingHints.VALUE_ANTIALIAS_ON);
    		g2.setPaint(new Color(0x333333));
    		g2.draw(new Line2D.Double(w/2, 0, w/2, 8)); // n
    		g2.draw(new Line2D.Double(0, h/2, 8, h/2)); // w
    		g2.draw(new Line2D.Double(w/2, h-8, w/2, h)); // s
    		g2.draw(new Line2D.Double(w-8, h/2, w, h/2)); // e
    		g2.dispose();
    		return image;
    	}
    }
    
    //----------------------------------------
    class ButtonManager implements ActionListener {
    	JButton[] buttons = new JButton[0];
    
    	public void actionPerformed(ActionEvent e) {
    		String ac = e.getActionCommand();
    			if(ac.equals("add")) {
    			getButton("remove").setEnabled(false);
    			enable(true);
    		
    			} else if(ac.equals("remove")) {
    				getButton("add").setEnabled(false);
    				enable(true);
    				} else {
    
    					reset();
    					}
    				}
    	
    	public void reset() {
    		getButton("add").setEnabled(true);
    		getButton("remove").setEnabled(true);
    		enable(false);
    	}
    
    	private void enable(boolean enable) {
    		getButton("cancel").setEnabled(enable);
    	}
    
    	public void add(JButton button) {
    		button.addActionListener(this);
    		int size = buttons.length;
    		JButton[] temp = new JButton[size+1];
    		System.arraycopy(buttons, 0, temp, 0, size);
    		temp[size] = button;
    		buttons = temp;
    	}
    
    	private JButton getButton(String target) {
    		for(int j = 0; j < buttons.length; j++) {
    		if(buttons[j].getActionCommand().equals(target))
    		return buttons[j];
    	}
    	return null;
    	}
    
    } // end class
    When u run the code the green line starts somewhere from the left corner top of the applet window and does not start from the points. Can some on give me an explanation or help me over come this??????

    Please do run the code to check it out

    Thanks in advance

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

Similar Threads

  1. JVM creation failed
    By RogerP in forum NetBeans
    Replies: 12
    Last Post: 10-08-2011, 09:33 PM
  2. Database creation using java code...
    By Sahiba in forum JDBC
    Replies: 1
    Last Post: 07-16-2009, 11:37 PM
  3. bmp creation
    By makpandian in forum New To Java
    Replies: 1
    Last Post: 12-17-2008, 05:33 PM
  4. Java GUI creation help?
    By sabrown311313 in forum New To Java
    Replies: 4
    Last Post: 09-13-2008, 06:28 AM
  5. Java Applet re-creation problem
    By Mikalai.Kardash in forum Java Applets
    Replies: 0
    Last Post: 07-23-2007, 02:09 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •