2012-02-25 85 views
1

我想查找长度的行。我使用鼠标事件初始化坐标x1,y1,x2,y2。当我试图找到距离,如下图所示:在JAVA中查找行的长度

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; 
    } 
} 

Main.java

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();      
    } 
    ....................... 
    ........................ 
} 

这个代码是找到从坐标线的长度,但是当我找到一个线的长度画在我的屏幕从RULER它看起来没有看到我从上述代码获得相同的长度。那么,这是什么问题,我如何找到确切的长度?

+3

您有任何关于显示器的规格?您确定工具包报告的屏幕分辨率是否正确? – claesv 2012-02-25 08:10:10

+0

我认为它是正确的...但不确定.. – Parth 2012-02-25 08:16:25

回答

2

您可以使用GraphicsDeviceGraphicsConfigurationgetNormalizingTransform()来确定所需的几何形状。特别地,标识变换指示“用户空间中的72个单位等于设备空间中的1英寸”。

还考虑Math.hypot()更准确。