单击鼠标按钮时无法读取

问题描述 投票:0回答:1

(根据建议进行编辑)

尝试为编程项目实现编码解决方案。

  • 处理鼠标点击的私有事件处理程序,通过左键点击添加一个点, 右键单击删除一个点,然后重新计算最大点集。

我的实现(或者我缩小了错误范围的地方):

public class PointPane extends Pane {
    private final ArrayList<Point> points;

    public PointPane(ArrayList<Point> points) {
        this.points = points;
        drawPoints();
        this.setOnMouseClicked(this::handleMouseClick);
    }

    // this is the section with the issue

    private void handleMouseClick(MouseEvent event) {

        // after entry it should be checking for the left or right mouse button, but
        // it does not enter either the if or the else if and goes directly to
        // drawPoints();

        if (event.isPrimaryButtonDown()) { // Left click
            points.add(new Point(event.getX(), event.getY()));

        } else if (event.isSecondaryButtonDown()) { // Right click            
            Point pointToRemove = null;
            for (Point point : points) {
                if (Math.abs(point.getX() - event.getX()) 
                        < 5 && Math.abs(point.getY() - event.getY()) < 5) {
                    pointToRemove = point;
                    break;
                }
            }
            if (pointToRemove != null) {
                points.remove(pointToRemove);
            }
        }
        drawPoints();
    }

java javafx
1个回答
0
投票

对于未来的读者:

问题是 TO 需要听

click event
,但他听的是
mouse down event

解决方案是@Abra 在评论中提供的:

来自文档(关于方法

isPrimaryButtonDown
):如果当前按下主按钮,则返回 true。对于“鼠标点击”事件来说,情况并非如此。我认为你需要方法
getButton()
,即
if (MouseButton.PRIMARY == event.getButton())

© www.soinside.com 2019 - 2024. All rights reserved.