javafx - 当移动其中的物体时,如何防止一个组自行移动?

标签 javafx bluej

似乎当我将圆移到方 block 组之外时,它会移动方 block ,即使没有代码可以做到这一点。我 99% 确定这是因为该组尝试自动居中,但只有当我更改组的比例时它才会这样做。这是演示我当前遇到的问题的代码。(请注意,我根本不希望方 block 移动)

import javafx.application.Application;
import javafx.scene.shape.Circle;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.util.Duration;
import javafx.scene.layout.Pane;
import javafx.scene.Scene;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.scene.Group;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;

public class Test extends Application
{
    private static Circle circle = new Circle(0, 0, 10);
    private static Group group = new Group(circle);
    private static Group mainPane = new Group(group);
    private Scene scene = new Scene(mainPane, 600, 600);
    public void start(Stage stage){
        circle.setViewOrder(-1);
        for(int i = 0; i < 100; i++){
            Rectangle backGround = new Rectangle(-10, -10, 20, 20);
            backGround.setLayoutX((i - (int)(i * .1) * 10) * 20 - 100);
            backGround.setLayoutY((int)(i * .1) * 20 - 100);
            group.getChildren().add(backGround);
        }
        
        /*This line causes the problem*/group.setScaleX(1.5);
        /*This line causes the problem*/group.setScaleY(1.5);
        group.setLayoutX(200);
        group.setLayoutY(200);
        circle.setFill(Color.RED);
        Timeline time = new Timeline();
        time.setCycleCount(Timeline.INDEFINITE);
        KeyFrame frame = new KeyFrame(Duration.millis(1), new EventHandler<ActionEvent>(){
            @Override public void handle(ActionEvent e){
                circle.setLayoutX(circle.getLayoutX() + .1);
                if(circle.getLayoutX() > 150) circle.setLayoutX(0);                
            }
        });
        time.getKeyFrames().add(frame);
        time.playFromStart();
        stage.setScene(scene);
        stage.show();
    }
}

最佳答案

所以我认为问题在于 scaleX/scaleY 使用节点的中心作为枢轴点。将其与 Group 随着 Circle 向右移动而增大的事实相结合,并且缩放会导致 Group “移动”,因为中心成为枢轴点。

当我更换时:

/*This line causes the problem*/group.setScaleX(1.5);
/*This line causes the problem*/group.setScaleY(1.5);

与:

// javafx.scene.transform.Scale
Scale scale = new Scale(1.5, 1.5);
group.getTransforms().add(scale);

你的问题就消失了。与 scaleX/scaleY 不同,Scale 使用的枢轴点不会随着 Group 的增长而自动调整。请注意,上面的 Scale 使用 (0,0) 作为轴心点。我认为这没问题,但如果你愿意,你可以将枢轴点设置为组的初始中心点(只是不要不断更新枢轴点,否则你可能会遇到与之前相同的问题)。

关于javafx - 当移动其中的物体时,如何防止一个组自行移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69861414/

相关文章:

java - JFrame Pane 在重新打开时不允许单击另一个按钮

java - 使用字符串 - Public int length()

java - 如何使用 id 获取 JavaFx 中的元素?

JAVAFX : Tableview row selection behaviour

java - Bluej打包一个项目

java - 尝试使用带有 'menu' 的 For 循环

java - 无法对齐堆栈 Pane 内的文本字段

javafx - Java FX 删除 TreeView 根项

java - 用Java模拟触摸滚动

java - 从 Eclipse 进行单个方法调用,无需类