How to use Guice in Swing application
- by Gerco Dries
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.