JavaFx scene lookup returning null

后端 未结 1 541
孤城傲影
孤城傲影 2020-12-07 04:09
Button btn = new Button(\"ohot\");
btn.setId(\"testId\");
itemSection.getChildren().add(btn);
Node nds = itemSection.lookup(\"‪#‎testId‬\");

What i

相关标签:
1条回答
  • 2020-12-07 04:44

    Lookups in conjunction with applyCSS

    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, as the layout operation can effect scene graph attributes.

    So you could do this:

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

    Alternate lookup after showing a stage

    Note that some operations in JavaFX, such as initially showing a Stage or waiting for a pulse to occur, will implicitly execute a CSS application, but most operations will not.

    So you could also do this:

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

    On CSS based lookups VS explicit references

    Storing and using explicit references in your code is often preferred to using lookups. Unlike a lookup, using an explicit reference is type safe and does not depend upon a CSS application. Generating explicit references can also be facilitated by using JavaFX and FXML with the @FXML annotation for type-safe reference injection. However, both lookup and explicit reference approaches have valid use cases, so it is a really just a matter of using the right approach at the right time.

    0 讨论(0)
提交回复
热议问题