JavaFx:parent.lookup返回null

3 java javafx

我使用osgi + cdi,我有以下代码:

Parent parent=null;
FXMLLoader fxmlLoader=getFxmlLoader();
try {
    parent = (Parent)fxmlLoader.load(getFxmlStream("tasklist.fxml"));
} catch (IOException ex) {
    Logger.getLogger(TestGoView.class.getName()).log(Level.SEVERE, null, ex);
}
ComboBox comboBox=(ComboBox) parent.lookup("#testComboBox");
if (comboBox==null){
    System.out.println("COMBOBOX NULL");
}else{
    System.out.println("COMBOBOX NOT NULL");
}
Run Code Online (Sandbox Code Playgroud)

我有以下tasklist.fxml

<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="440.0" prefWidth="757.0" xmlns="http://javafx.com/javafx/8.0.60-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.techsenger.testgo.core.adm.task.list.TaskDirListController">
   <children>
      <HBox>
         <children>
            <ToolBar maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" nodeOrientation="RIGHT_TO_LEFT" HBox.hgrow="SOMETIMES">
               <items>
                  <ComboBox fx:id="testComboBox" maxWidth="1.7976931348623157E308" nodeOrientation="LEFT_TO_RIGHT" />
               </items>
            </ToolBar>
         </children>
      </HBox>
   </children>
</VBox>
Run Code Online (Sandbox Code Playgroud)

但是parent.lookup("#testComboBox")返回null.怎么解释呢?我已多次检查ID的名称.

var*_*ren 6

这是因为您在屏幕上显示父级之前尝试使用查找.

    Pane root = FXMLLoader.load(getClass().getResource("tasklist.fxml"));

    System.out.println(root.lookup("#testComboBox")); //returns  null
    primaryStage.setScene(new Scene(root));
    primaryStage.show();
    System.out.println(root.lookup("#testComboBox")); //returns 
    // ComboBox[id=testComboBox, styleClass=combo-box-base combo-box]
Run Code Online (Sandbox Code Playgroud)


Jam*_*s_D 6

您可以将所需的逻辑放入控制器类中,而不必使用仅在渲染场景后才能使用的查找。您可以通过注释将元素从FXML文件注入到控制器类中@FXML

public class TaskDirListController {

    @FXML
    private ComboBox<...> testComboBox ;

    public void initialize() {
        System.out.println(testComboBox);
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

查询通常并不可靠,我建议避免使用它们。如果您确实需要从控制器以外的其他类访问FXML文件中定义的内容,则要做的第一件事就是考虑对内容进行重组,以使您无需这样做:这实际上表明您的总体设计是错误的。

如果你真的需要这种出于某种原因,最好还是使用FXMLLoadernamespace不是查找:

Parent parent=null;
FXMLLoader fxmlLoader=getFxmlLoader();
try {
    parent = (Parent)fxmlLoader.load(getFxmlStream("tasklist.fxml"));
    ComboBox<?> comboBox = (ComboBox<?>) fxmlLoader.getNamespace().get("testComboBox");
    System.out.println(comboBox);
} catch (IOException ex) {
    Logger.getLogger(TestGoView.class.getName()).log(Level.SEVERE, null, ex);
}
Run Code Online (Sandbox Code Playgroud)