假设我有一些 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();
}
}
Run Code Online (Sandbox Code Playgroud)
向节点的localToSceneTransform属性添加监听器。
node.localToSceneTransformProperty().addListener((o, oldValue, newValue) -> {
System.out.println("transform may have changed");
});
Run Code Online (Sandbox Code Playgroud)
请注意,这
除此之外boundsInLocal,如果您还想收到节点本身大小变化的通知,则可能需要该属性的侦听器。