JavaFx 场景查找返回 null

JavaFx scene lookup returning null

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

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

结合应用查找CSS

Lookups are based on CSS. So CSS needs to be applied to the scene for you to be able to lookup items in the scene. See the applyCSS documentation for more information. To get accurate results from your lookup, you might also want to invoke layout,布局操作会影响场景图属性

所以你可以这样做:

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

显示阶段后的备用查找

请注意,JavaFX 中的某些操作(例如最初 showing a Stage or waiting for a 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 注释用于 type-safe 引用注入,也可以促进生成显式引用。然而,查找和显式引用方法都有有效的用例,所以这实际上只是在正确的时间使用正确的方法的问题。