SWTLoader, create self-contained SWT apps

Logo del programma SWTLoader

L’articolo che segue è in lingua inglese, è disponibile anche la traduzione in italiano.

SWT and SwingWT-based programs, as well as all other Java programs with native libraries, are often tricky to deploy.
Because native libraries are needed an installer must be created, unless you tell users to manually copy files in a directory in the PATH (assuming that they know what it is).
Jar files would be preferrable, because a double-click would launch them on most platforms, but the Java Virtual Machine cannot use native libraries if you put them in Jars, instead the -Djava.library.path commandline switch must be used.
SWTLoader is an elegant hack to avoid all this, allowing you to deploy self-contained, self-extracting native libraries such as SWT in a single Jar file.

How to use it

You can use SWTLoader following these three easy steps:

  • import net.moioli.swtloader.*; in the class with the main() method;
  • Create a new SWTLoader as the first instruction in the main method, like this:
public static void main(String[] args){
new SWTLoader("packagename.jar");
  • Include in the Jar file the needed .dll, .so or .jnilib files. You can do that by hand (Jars are just ZIP files) or using a script like this Apache Ant build.xml file:


<target name="demo-SwingWT-linux" >
  <javac srcdir="${srcDir}" destdir="${buildDir}">
      <pathelement path="swt.jar"/>
      <pathelement path="swt-pi.jar"/>
    <include name="**/*.java" />
  <unjar src="$swt.jar" dest="${buildDir}"/>
  <unjar src="$swt-pi.jar" dest="${buildDir}"/>
  <copy todir="${buildDir}">
    <fileset dir="${swtLinuxLibDir}/">
    <include name="*.so"/>
  <jar destfile="${buildDir}/demo-SwingWT-linux.jar" basedir="${buildDir}">
  <fileset dir="${buildDir}" >
    <include name="**/*.class" />
    <include name="**/*.so"/>
    <attribute name="Main-Class" value="SWTDemo"/>

Users, just double-clicking the produced Jar file, will get a fully functional and SWT-enabled JVM.

How does it work?

The inner workings of the script are quite easy: first, it creates a temporary directory, then it unpacks the library files in it and finally it re-invokes the JVM with the right -D option. Note that you’ll have only one JVM running at a time: the first VM instance will be terminated safely.
Also, if SWT is already loadable, none of these actions will be performed.

Get it

SWTLoader is free and published under the GPL license. If you need a non-GPL’d version (eg. for commercial purposes) email me: silvio at moioli dot net

Comments are closed.