javafx - 如何识别场景中的节点边界变化?
问题描述
假设我有一些 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();
}
}
解决方案
为节点的localToSceneTransform
属性添加一个监听器。
node.localToSceneTransformProperty().addListener((o, oldValue, newValue) -> {
System.out.println("transform may have changed");
});
请注意,这
- 产生一些“误报”,即如果职位实际上没有改变,它可能会通知您。
- 向节点注册过多的侦听器可能会降低应用程序的性能,因为这样做涉及侦听层次结构中所有节点的更改,直到根节点。
除此之外boundsInLocal
,如果您还希望收到节点本身大小变化的通知,则可能需要该属性的侦听器。
推荐阅读
- python - 有什么方法可以使集合运算符与存储对象的集合一起工作?
- c# - 订单状态发布方法没有被调用 web api 2
- amazon-web-services - AWS 是否支持 Oracle 自治数据库?
- go - 乘以 *float32 和 int 值
- joomla - 错误:无法启动应用程序:在 joomla 中找不到类“JSessionHandlerJoomla”
- javascript - Javascript恢复部分字符串不起作用?
- c# - “当前上下文中不存在名称‘fieldname’的原因
- java - 如何将变量值传递给套接字字符串
- julia - 有没有办法将我的函数转换为Julia中DifferentialEquations.jl中的标准ODE函数?
- nginx - 使用 caddy 或 nginx 时,如何让代理忽略 url 前缀?