I have written a Java GUI using SWT. I package the application using an ANT script (fragment below).
<jar destfile="./build/jars/swtgui.jar" filesetmanifest="mergewithoutmain">
<manifest>
<attribute name="Main-Class" value="org.swtgui.MainGui" />
<attribute name="Class-Path" value="." />
</manifest>
<fileset dir="./build/classes" includes="**/*.class" />
<zipfileset excludes="META-INF/*.SF" src="lib/org.eclipse.swt.win32.win32.x86_3.5.2.v3557f.jar" />
</jar>
This produces a single jar which on Windows I can just double click to run my GUI. The downside is that I have had to explicitly package the windows SWT package into my jar.
I would like to be able to run my application on other platforms (primarily Linux and OS X). The simplest way to do it would be to create platform specific jars which packaged the appropriate SWT files into separate JARs.
Is there a better way to do this? Is it possible to create a single JAR which would run on multiple platforms?
I have a working implementation which is now referenced from the SWT FAQ.
This approach is now available to use as an ANT task: SWTJar
[EDIT] SWTJar has now been updated to use Alexey Romanov’s solution as described above.
build.xml
First I build a jar containing all of my application classes.
Next, I build a jar to contain all of the following:
Here is the fragment from build.xml.
TraceClientLoader.java
This loader class uses the jar-in-jar-loader to create a ClassLoader which loads classes from two jars.
Once we have this classloader we can launch the actual application main method using reflection.
[EDIT] As stated above, for those looking for the “jar-in-jar classloader”: It’s included in Eclipse’s JDT (the Java IDE built on Eclipse). Open org.eclipse.jdt.ui_*version_number*.jar with an archiver and you will find a file jar-in-jar-loader.zip inside. I renamed this to jar-in-jar-loader.jar.
intrace-ui.jar – this is the jar which I built using the process described above. You should be able to run this single jar on any of win32/64, linux32/64 and osx32/64.
[EDIT] This answer is now referenced from the SWT FAQ.