JRuby + SWT = Future Cross Platform Ruby Desktop App Development?

By Peter Cooper





(Disclaimer: I'm no Java wiz, so if I get anything wrong about Java or its libraries, post comments!)



The SWT (Standard Widget Toolkit) is a GUI widget toolkit for the Java platform. Unlike AWT and Swing, it uses the local operating system's own controls. This means you can develop Java apps that 'look native' on multiple platforms. The popular Eclipse IDE uses SWT to work and looks graphically native on multiple platforms (as does Azureus). SWT is also, reputedly, faster than the other alternatives. Sounds great for developers, right? Java developers.. sure.

I decided SWT was too good an idea to not investigate, so I downloaded JRuby 0.9.1 (a Ruby interpreter written in Java and which provides access to Java classes from Ruby) and set to work. All I had to do was copy the swt.jar and supporting files for my platform into the jruby/lib folder, add "-Djava.library.path=$JRUBY_BASE/lib" into the Java call in the bin/jruby helper script.. and then I could write and run code like this:

require ' java ' module SWTTest include_package ' org.eclipse.swt ' include_package ' org.eclipse.swt.layout ' include_package ' org.eclipse.swt.widgets ' Display . setAppName " Ruby SWT Test " display = Display . new shell = Shell . new display shell . setSize ( 450 , 200 ) layout = RowLayout . new layout . wrap = true shell . setLayout layout shell . setText " Ruby SWT Test " label = Label . new ( shell , SWT :: CENTER ) label . setText " Ruby SWT Test " Button . new ( shell , SWT :: PUSH ). setText (" Test Button 1 ") shell . pack shell . open while (! shell . isDisposed ) do display . sleep unless display . readAndDispatch end display . dispose end

This works on OS X (screenshot of result is at the top of this post) but it's all generic so if you can get JRuby and the SWT JAR and support files for your platform, this same code will render a native looking window with a label and button control on whatever platform you're running. The major downsides so far are that it's a bit unstable (if I move the window much, the app crashes) and I can't seem to create events for the controls, although I think this might be due to my lack of Java nous. Also.. it's an experimental piece of software running on an experimental compiler, so it's far from ready for real use, and there are undoubtedly better solutions, but if you like to hack...