java - 为什么不在 JavaFX Controller 中注入(inject)成员?

标签 java dependency-injection javafx fxml

我有以下 FXML:

<BorderPane fx:controller="mypackage.MainStage" id="BorderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2">
  <bottom>
    <ToolBar>
      <items>
        <Slider id="slider" prefWidth="443.0" />
        <Label text="Record:" />
        <TextField prefWidth="46.0" />
        <Label text=" of " />
        <Label id="totalLabel" text="0" />
      </items>
    </ToolBar>
  </bottom>
  <center>
    <Pane id="mainPane" prefHeight="200.0" prefWidth="200.0" />
  </center>
  <top>
    <ToolBar>
      <items>
        <Button mnemonicParsing="false" text="Load more" />
      </items>
    </ToolBar>
  </top>
</BorderPane>

和以下 Controller 代码:

public class MainStage implements Initializable {

    @FXML
    private Pane mainPane;

    @FXML
    private Label totalLabel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        totalLabel.setText("245");
    }

}

和下面的应用程序代码

public class MyClass extends Application
{

    @Override
    public void start(Stage stage) throws Exception {

        Parent root = FXMLLoader.load(getClass().getResource("MainStage.fxml"));

        Scene scene = new Scene(root);

        stage.setTitle("MyClass");
        stage.setScene(scene);
        stage.show();


    }

    public static void main( String[] args )
    {
        launch(args);
    }


}

如果我将断点设置为 initialize(),我会看到它被调用,但成员为 null

为什么不注入(inject)?

最佳答案

因为我使用了 id 而要使用 fx:id 标签。

关于java - 为什么不在 JavaFX Controller 中注入(inject)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107604/

相关文章:

java - Mockito:如何 stub getter setter

java - 从 url java 打印 pdf

java - 图像按钮事件不起作用

java - Jersey 和 HK2 - 注入(inject)当前用户

c# - 为什么 Light Inject 的源代码都在一个 .cs 文件中

java - 使用实现 Comparator 作为参数的类时出现问题

javascript - 使用依赖注入(inject)时,通过引用调用服务或直接调用服务有区别吗?

java - JavaFX TreeView 的嵌套路径

java - Netbeans 7.1.2 JavaFX UnsatisfiedLinkError

Javafx HBox Hgrow(SOMETIMES)子滚动 Pane 节点如何获取宽度?