title: Find Length of Line in JAVA
body: <p>I want to find a length of line. I have initialize a coordinates x1,y1,x2,y2 using mouse Events. When i try to find distance as shown below:</p>
  
  <pre><code>public class LineFunctions {
      static int dpi;
      static double pixel_per_cm;
      public LineFunctions(){
          Toolkit tk;
          tk=Main.frame.getToolkit();
          dpi=tk.getScreenResolution();
          pixel_per_cm=dpi/2.54;
      }
      public double lengthInPixel(int x1,int y1,int x2,int y2){
          double length_in_pixel;
          double x=Math.pow((x2-x1), 2);
          double y=Math.pow((y2-y1), 2);
          length_in_pixel = Math.sqrt(x+y);
          return length_in_pixel;
      }
      public double lengthInCm(int x1,int y1,int x2,int y2){
  
          double length_in_pixel=lengthInPixel(x1,y1,x2,y2);
          double length_in_cm = length_in_pixel / pixel_per_cm;
          System.out.println("Length in Cm= "+length_in_cm);
          return length_in_cm;
      }
  }
  </code></pre>
  
  <p>Main.java</p>
  
  <pre><code>public class Main {
      public static JFrame frame;
      public static void main(String ar[]) {
          frame=new JFrame("LINE FRAME");
      }
      static class ImageComponent extends JComponent implements MouseListener {
          Line2D line;
              int x1,y1,x2,y2;
              public ImageComponent() {
                  addMouseListener(this);
                  addMouseMotionListener(this);
      }
              @Override
              public void paintComponent(Graphics g){
                    super.paintComponent(g);
                    Graphics2D gd=(Graphics2D)g;
                    line=new Line2D.Double(x1,y1,x2,y2);
                    gd.draw(line);
              }
              @Override
      public void mousePressed(MouseEvent e) {
  
          x1=e.getX();
                      y1=e.getY();
      }
  
      @Override
      public void mouseReleased(MouseEvent e) {
                      x2=e.getX();
                      y2=e.getY();
                      LineFunctions lf=new LineFunctions();
                      double length=lf.lengthInCm(x1,y1,x2,y2);
                      System.out.println("Line Length="+length);
                      repaint();                    
      }
      .......................
      ........................
  }
  </code></pre>
  
  <p>This code finds the length of line from the coordinates, but when i find the length of a line drawn on my screen from the <strong>RULER</strong> it doesn't saw me the same length as i got from the above code. So, What is the Problem with this and how can i find the exact length of line?</p>