JavaFX - 调整大小 and/or 移动节点(例如 TextFields)

JavaFX - Resize and/or move nodes(e.g. TextFields)

我正在寻找移动 nodes(在我的例子中是 TextField)以及调整它们大小的方法。

下面是一个基本示例:

public class Main extends Application{

private static final Pane pane = new Pane();

public void start(Stage stage) {
    TextField txtField = new TextField();
    txtField.relocate(300, 0);
    Button btnS = new Button("Change size");
    btnS.setPrefSize(100, 20);
    btnS.relocate(0, 0);
    btnS.setOnAction(e -> {
        ScaleTransition transition = new ScaleTransition(Duration.millis(300), txtField);
        transition.setByX(2);
        transition.play();
    });

    Button btnP = new Button("Change Position");
    btnP.setPrefSize(100, 20);
    btnP.relocate(110, 0);
    btnP.setOnAction(e -> {
        PathTransition transition = new PathTransition();
        transition.setNode(txtField);
        transition.setPath(new Path(new MoveTo(300, 50)));
        transition.play();
    });

    pane.getChildren().addAll(btnS, btnP, txtField);
    Scene scene = new Scene(pane);
    pane.setPrefSize(500, 100);
    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) {
launch();
}
}

我希望 TextField 仅将其宽度更改为右侧(因此它看起来像从左到右 "sliding"(变宽))。我认为我的尝试是错误的,因为我不想缩放它,但是 resize 它(尽管 TextField 的缩放有效)。 或者是通过创建一个循环来改变大小的唯一方法,它会在每次迭代时将数量 i 添加到宽度?

另一个 Button 应该移动 TextField。这次我觉得我的尝试是对的,但是代码不起作用,我无法解释。

有人能帮我吗?谢谢。

就改变 TextField 的宽度而言。循环将不起作用,因为您会阻塞负责布局的线程。如何调整节点大小取决于父级,因为显示宽度由父级在布局期间确定。在这种情况下,您可以简单地使用 Timeline:

prefWidth 属性 设置动画
Timeline timeline = new Timeline(
        new KeyFrame(Duration.ZERO, new KeyValue(txtField.prefWidthProperty(), txtField.getWidth())),
        new KeyFrame(Duration.millis(300), new KeyValue(txtField.prefWidthProperty(), 300)));

timeline.play();

The other Button should move the TextField. This time I think my attempt is right, however the code doesn't work, which I can't explain.

看看你使用的路径是什么样子的。没有绘制任何内容,因为您只使用了一个 MoveTo 元素。您要么需要修复路径,要么我们更简单 TranslateTransition:

TranslateTransition transition = new TranslateTransition(Duration.millis(400), txtField);
transition.setToY(50);
transition.play();

注意:您可能需要调整代码以获得重复点击所需的效果。