How do you check if a mouse press is on a line in Java

点点圈 提交于 2020-04-18 05:43:20

问题


I am creating a java application and wanting to make it so that a user can click on a line in order to make an event occur. The line is simply defined by its 2 endpoints, both of which have a x and a y coordinate.

Any ideas on how I can I can check if a position collected from the mouse press event (with a x and y coordinate) can be checked to see if it is on this line?

I want to make it so that the hit detection for the line is a little bit forgiving for the user so that as long as the mouse press is quite close to the line, it will be accepted.


回答1:


The general idea is, you should calculate the distance between the clicked point and your line. If the distance is less than say 2 pixels, consider the click to be close enough.

You can do the math yourself if you're so inclined. In the Java standard library, the java.awt.geom.Line2D class has methods to check the distance between a point and a line or a line segment.

double distance = Line2D.ptSegDist​(lineStartX, lineStartY, 
                                   lineEndX, lineEndY,
                                   clickX, clickY);

if (distance < 2) {
    // success!
}


来源:https://stackoverflow.com/questions/60915867/how-do-you-check-if-a-mouse-press-is-on-a-line-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!