如何在Swing应用程序中使用Guice [英] How to use Guice in Swing application

查看:201
本文介绍了如何在Swing应用程序中使用Guice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swing应用程序,我想从意大利面转换到使用依赖注入与Guice。使用Guice提供配置和任务队列等服务是非常好的,但我现在正在开始使用该应用程序的GUI,并且不确定如何继续。



应用程序基本上是一个 JFrame ,其中有一些 JTabbedPane 中的选项卡。每个选项卡是一个单独的 JPanel 子类,其中列出了各种组件,并需要服务来执行某些按钮时的操作。



在当前的应用程序中,这看起来像这样:

  @Inject 
public MainFrame(SomeService service,Executor ex,Configuration config){
tabsPane = new JTabbedPane();

//为每个选项卡创建面板,并将它们添加到tabbedpane
somePanel = new SomeTabPanel(service,ex,config);
tabsPane.addTab(Panel 1,somePanel);

someOtherPanel = new SomeOtherTabPanel(service,ex,config);
tabsPane.addTab(Panel 2,someOtherPanel);

...做更多的东西
}

显然,这并不完全符合DI最佳做法。我不想让 @Inject 选项卡,因为这会让我有一个具有数十个参数的构造函数。我想使用Guice将所需的依赖项注入到我需要的任何选项卡对象中,而无需将所有这些依赖关系传递给选项卡构造函数。



所有依赖项对于标签对象是我的模块知道的服务,所以基本上我想要的是/ / em>我想做的是向Guice询问所需的对象,让他们为我建造。

解决方案

可以使用多重绑定将所有标签绑定为 Set ?如果他们实现了一些允许您使用该标签的界面的界面,则可以通过添加集合中的选项卡循环。你可能需要找出一些东西,只要点击选项卡。


I have a Swing application that I would like to convert from spaghetti to using dependency injection with Guice. Using Guice to provide services like configuration and task queues is going great but I'm now starting on the GUI of the app and am unsure of how to proceed.

The application is basically a JFrame with a bunch of tabs in a JTabbedPane. Each of the tabs is a separate JPanel subclass that lays out the various components and needs services to perform actions when certain buttons are pressed.

In the current application, this looks somewhat like this:

@Inject
public MainFrame(SomeService service, Executor ex, Configuration config) {
    tabsPane = new JTabbedPane();

    // Create the panels for each tab and add them to the tabbedpane
    somePanel = new SomeTabPanel(service, ex, config);
    tabsPane.addTab("Panel 1", somePanel);

    someOtherPanel = new SomeOtherTabPanel(service, ex, config);
    tabsPane.addTab("Panel 2", someOtherPanel);

    ... do more stuff
}

Obviously, this doesn't exactly follow DI best practices. I don't want to have to @Inject the tabs because that would get me a constructor with dozens of parameters. I do want to use Guice to inject the required dependencies into whatever tab objects I need without me having to pass all of those dependencies to the tab constructors.

All of the dependencies for the tab objects are services that my Module knows about, so basically all I think I want to do is to ask Guice for the required objects and have them constructed for me.

解决方案

Could you use Multibinding to bind all of your tabs as a Set? If they implemented some interface that allowed you to get the name to use for the tab, you could then just loop through adding the tabs from the set. You'd probably need to figure something out as far as ordering the tabs though.

这篇关于如何在Swing应用程序中使用Guice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆