如何检查鼠标是否在Java中的一行上 [英] How do you check if a mouse press is on a line in Java

查看:75
本文介绍了如何检查鼠标是否在Java中的一行上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Java应用程序,并希望创建它,以便用户可以单击一行以使事件发生.该线仅由其2个端点定义,这两个端点均具有x和y坐标.

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.

关于如何检查从鼠标按下事件(带有x和y坐标)中收集到的位置的任何想法,是否可以查看它是否在此行上?

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.

推荐答案

通常的想法是,您应该计算单击的点与直线之间的距离.如果距离小于2像素,则认为点击距离足够近.

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.

如果您愿意,可以自己做数学.在Java标准库中,

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

这篇关于如何检查鼠标是否在Java中的一行上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆