如何使用spring依赖注入连接多个fxml控制器?

时间:2014-04-07 10:56:39

标签: java spring spring-mvc dependency-injection javafx

我阅读了一些基本示例的春季教程,我对如何正确连接事物感到困惑。

麻烦的是,我想使用应用程序上下文来提取单例控制器引用,但我读了一些其他主题,除非绝对必要,否则不应直接访问应用程序上下文。我想我应该使用构造函数来实例化我想要的引用,但是这里的事情对我来说都很模糊。

我有几个fxml文件的javafx应用程序。我有一个主要的fxml,其他的是在main中动态加载的。

我将使用简化代码,例如两个fxml控制器, MainController.java (对于主要fxml)和 ContentController.java (对于内容fxml)< / p>

我们的想法是内容fxml有TabPane,而主fxml有按钮,可以在ContentController上的TabPane中打开新标签。

我目前正在做这样的事情

bean xml:     

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="contentController"
class="ContentController"
scope="singleton" />
</beans>

MainControler:

public class MainOverlayControler {

ApplicationContext context;

@FXML
private BorderPane borderPane;

@FXML
private void initialize() {
    loadContentHolder();
}
@FXML
private Button btn;

@FXML
private void btnOnAction(ActionEvent evt) {
    ((ContentController)context.getBean("contentController")).openNewContent();
}

private void loadContentHolder() {
    //set app context
    context = new ClassPathXmlApplicationContext("Beans.xml");

    Node fxmlNode;
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setController(context.getBean("contentController"));

    try {
    fxmlNode = (Node)fxmlLoader.load(getClass().getResource("Content.fxml").openStream());
    borderPane.setCenter(fxmlNode);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

ContentController:

public class ContentController {
@FXML
private TabPane tabPane;

public void openNewContent() {
    Tab newContentTab = new Tab();
    newContentTab.setText("NewTab");
    tabPane.getTabs().add(newContentTab);
    }
}

主要课程:

public class MainFX extends Application {
@Override
public void start(Stage primaryStage) {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        Parent root = (Parent) fxmlLoader.load(getClass().getResource("main.fxml").openStream());
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
    e.printStackTrace();
    }
public static void main(String[] args) {
    launch(args);
    }
}

问题: 我想知道如何用构造函数DI做同样的事情,或者如果我误解了这个概念,还有其他方法。

我需要能够打电话给&#34; openNewContent&#34;单元实例&#34; ContentController&#34;来自其他多个控制器。

1 个答案:

答案 0 :(得分:3)

阅读有关JavaFX和Spring集成的更多信息。我推荐Stephen Chin

系列

基本上,您需要将JavaFX类嵌入到Spring上下文生命周期中,并且在链接文章中对它进行了很好的描述。

您还可以在GitHub上查看他的示例项目,其中使用JavaFX 2.1中引入的控制器工厂简化了代码(check here

相关问题