• Share this article:

Using Swing in an Eclipse RCP application

Thursday, May 18, 2006 - 17:01 by Wayne Beaton

I’ve finally made it to JavaOne. It’s my first time here and I have to admit that I’m a little overwhelmed. It’s a huge conference.

Today, the title of my blog is not an insane attempt to attract more traffic… I was working the Eclipse Foundation booth earlier today and was asked by a visitor about the possibility of building an Eclipse RCP application with a Swing-based user interface.

Why the heck would you want to do such a thing I can hear you ask? (actually, I think that might be somebody from the Oracle booth) There are several reasons. My favourite reason is Equinox. You can use the Equinox component framework under your Swing application. And if you do that, you can make use of things like extension points in your application. This, of course, makes your application very extendable. Of course, by using Equinox, you can also leverage the Eclipse update mechanism. Then, there’s help: you can probably use a little help with your Swing application. For me the biggest reason for using Equinox is simple: actual managed components.

By making your Swing-based user interface an Eclipse RCP application, you can make use of Eclipse plug-ins. Of course, if those plug-ins require SWT or the workbench to run (and you don’t want those things to be part of your application), you’re out of luck. But components packaged up as OSGi bundles can be used. So you could use the Hibernate bundles or package up other libraries that you might need as bundles to make them more easily updated later.

Running a Swing-based GUI from Eclipse RCP is pretty easy. When you generate an RCP applciation, it creates code like this:

public Object run(Object args) throws Exception {
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IPlatformRunnable.EXIT_RESTART;
}
return IPlatformRunnable.EXIT_OK;
} finally {
display.dispose();
}
}

The createAndRunWorkbench(…) part is where (oddly enough) the workbench gets created and run (I do love descriptive names).

You can change it to instead do Swing stuff:

public Object run(Object args) throws Exception {
JFrame frame = new JFrame("Eclipse RCP");
frame.setLocation(50, 50);
frame.add(new JTextField("Eclipse RCP application with Swing!"));
frame.pack();
frame.setVisible(true);
while (frame.isVisible())
Thread.currentThread().sleep(1000);
return IPlatformRunnable.EXIT_OK;
}

So… if you have an existing Swing application and you want to take advantage of the great features provided by the Eclipse RCP, you might consider this as a first step in your migration.