首页 > 解决方案 > 如何识别场景中的节点边界变化?

问题描述

假设我有一些 TextField 位于窗格布局结构的深处。我想添加侦听器或以某种方式识别 TextField 在场景中更改了其位置 (x, y)。问题是 - 我怎样才能以适当的、可重复使用的方式实现它?

我提供了一些测试代码。要重新创建,请拖动舞台边框,这将导致 TextField 位置发生变化。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class App extends Application {

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

    @Override
    public void start(Stage stage) throws Exception {
        TextField textField = new TextField();
        Button button = new Button("Button");

        HBox hBox = new HBox(textField, button);
        hBox.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);

        StackPane stackPane = new StackPane(hBox);
        stackPane.setPrefSize(600., 400.);
        Scene scene = new Scene(stackPane);
        stage.setScene(scene);
        stage.show();
    }
}

标签: javafx

解决方案


为节点的localToSceneTransform属性添加一个监听器。

node.localToSceneTransformProperty().addListener((o, oldValue, newValue) -> {
    System.out.println("transform may have changed");
});

请注意,这

  1. 产生一些“误报”,即如果职位实际上没有改变,它可能会通知您。
  2. 向节点注册过多的侦听器可能会降低应用程序的性能,因为这样做涉及侦听层次结构中所有节点的更改,直到根节点。

除此之外boundsInLocal,如果您还希望收到节点本身大小变化的通知,则可能需要该属性的侦听器。


推荐阅读