event.getX与圆圈的getLayoutX不对应

时间:2015-02-24 09:35:02

标签: java javafx nodes

我正在尝试创建一个程序来创建一个圆形实例,它获取鼠标点击的x和y坐标。然而,当试图获得圆圈的x时,它似乎等于0.

pane.setOnMouseClicked(new EventHandler<MouseEvent>() {
        public void handle(MouseEvent event) {
            final Circle newCircle = getCircle(event.getX(), event.getY(), 30);
            pane.getChildren().addAll(newCircle);
            final Timeline loop = new Timeline(new KeyFrame(Duration.millis(100), new EventHandler<ActionEvent>() {
                double deltaX = 2;
                double deltaY = 2;
                public void handle(ActionEvent event) {
                    newCircle.setLayoutX(newCircle.getLayoutX() + deltaX);
                    newCircle.setLayoutY(newCircle.getLayoutY() + deltaY);

                    final Bounds bounds = pane.getBoundsInLocal();
                    final boolean atRightBorder = newCircle.getLayoutX() >= (bounds.getMaxX()-newCircle.getRadius());
                    final boolean atLeftBorder = newCircle.getLayoutX() <= (bounds.getMinX()+newCircle.getRadius());
                    final boolean atBottomBorder = newCircle.getLayoutY() >= (bounds.getMinY()+newCircle.getRadius());
                    final boolean atTopBorder = newCircle.getLayoutY() <= (bounds.getMinY()-newCircle.getRadius());
                    if(atRightBorder || atLeftBorder)
                        deltaX *= -1;
                    if(atBottomBorder ||atTopBorder)
                        deltaY *= -1;
                }
            }));
            loop.setCycleCount(Timeline.INDEFINITE);
            loop.play();

我关注的是这一行:

final Circle newCircle = getCircle(event.getX(), event.getY(), 30);
            System.out.print(newCircle.getLayoutX());

即使event.getX参数不同,我的打印输出为“0.0”。

关于为什么会发生这种情况的任何想法?

编辑:getCircle():

 private Circle getCircle(double x, double y, double r){
    final Circle newCircle = new Circle(x, y, r);
    return newCircle;
}

1 个答案:

答案 0 :(得分:2)

您正在调用的构造函数是这样实现的:

public Circle(double centerX, double centerY, double radius) {
    setCenterX(centerX);
    setCenterY(centerY);
    setRadius(radius);
}

setCenterX()的实施位置:

public final void setCenterX(double value) {
    if (centerX != null || value != 0.0) {
        centerXProperty().set(value);
    }
}

getLayoutX()正在访问layoutX属性,该属性尚未由构造函数设置,因此它返回0.0

public final double getLayoutX() {
    return layoutX == null ? 0.0 : layoutX.get();
}

您需要设置layoutX属性,就像您在代码中所做的那样:

newCircle.setLayoutX(newCircle.getLayoutX() + deltaX);