gpt4 book ai didi

JavaFx 场景查找返回 null

转载 作者:行者123 更新时间:2023-12-01 11:28:57 25 4
gpt4 key购买 nike

Button btn = new Button("ohot");
btn.setId("testId");
itemSection.getChildren().add(btn);
Node nds = itemSection.lookup("‪#‎testId‬");

上面的代码有什么问题??我得到 nds=null 它应该是 btn

最佳答案

结合 applyCSS 查找

Lookups基于 CSS .因此,需要将 CSS 应用于场景,以便您能够在场景中查找项目。查看applyCSS文档以获取更多信息。要从查找中获得准确的结果,您可能还想调用 layout ,因为布局操作会影响场景图属性。

所以你可以这样做:

Button btn = new Button("ohot");
btn.setId("testId");
itemSection.getChildren().add(btn);
itemSection.applyCss();
itemSection.layout();
Node nds = itemSection.lookup("‪#‎testId‬");

显示阶段后的备用查找

请注意,JavaFX 中的某些操作,例如最初的 showing舞台或等待pulse发生,将隐式执行 CSS 应用程序,但大多数操作不会。

所以你也可以这样做:

Button btn = new Button("ohot");
btn.setId("testId");
itemSection.getChildren().add(btn);
stage.setScene(new Scene(itemSection);
stage.show();
Node nds = itemSection.lookup("‪#‎testId‬");

关于基于 CSS 的查找与显式引用

在代码中存储和使用显式引用通常优于使用查找。与查找不同,使用显式引用是类型安全的并且不依赖于 CSS 应用程序。通过将 JavaFX 和 FXML 与 @FXML 一起使用,也可以促进生成显式引用。类型安全引用注入(inject)的注解。然而,查找和显式引用方法都有有效的用例,所以这实际上只是在正确的时间使用正确的方法的问题。

关于JavaFx 场景查找返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34861690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com