gpt4 book ai didi

java - event.getX 与圆的 getLayoutX 不对应

转载 作者:行者123 更新时间:2023-12-02 04:56:45 25 4
gpt4 key购买 nike

我正在尝试创建一个程序来创建一个圆的实例,该实例获取鼠标单击的 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;
}

最佳答案

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

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

关于java - event.getX 与圆的 getLayoutX 不对应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28692235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com