Button btn = new Button("ohot");
btn.setId("testId");
itemSection.getChildren().add(btn);
Node nds = itemSection.lookup("?#?testId?");
Run Code Online (Sandbox Code Playgroud)
上面的代码有什么问题??我得到nds = null应该是btn
结合applyCSS进行查找
查找基于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?");
Run Code Online (Sandbox Code Playgroud)
显示阶段后的备用查询
请注意,JavaFX中的某些操作(例如最初显示舞台或等待脉冲发生)将隐式执行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?");
Run Code Online (Sandbox Code Playgroud)
在基于CSS的查询中VS显式引用
在代码中存储和使用显式引用通常比使用查找更可取。与查找不同,使用显式引用是类型安全的,并且不依赖CSS应用程序。通过将JavaFX和FXML与@FXML批注一起使用以进行类型安全的引用注入,也可以促进显式引用的生成。但是,查找和显式参考方法都具有有效的用例,因此,实际上只是在正确的时间使用正确的方法的问题。