Friday, November 23, 2007

Swing'in with Ruby and Javascript

I did a presentation last fall about Mozilla's Rhino (a Javascript engine found here.) One of the things demonstrated was the use of Java's Swing from Javascript. It's a tiny bit of simple code so I thought it might be interesting to look at the similarities and diffs between Rhino and JRuby's Java integration from this perspective.

Javascript (Rhino)


[sourcecode language="js"]
importPackage(Packages.javax.swing)

frame = new JFrame("My New Window")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(200,200)

panel = new JPanel()

button = new JButton("Click Me")

function clicked() {
print("button was clicked")
}

button.addActionListener(clicked)

panel.add(button)

frame.add(panel)
frame.pack()
frame.show()[/sourcecode]

Ruby (JRuby)


[sourcecode language="ruby"]
require "java"

include_class %w{
javax.swing.JFrame
javax.swing.JPanel
javax.swing.JButton
java.awt.event.ActionListener
}

frame = JFrame.new("My New Window")
frame.set_default_close_operation(JFrame::EXIT_ON_CLOSE)
frame.set_size(200,200)

panel = JPanel.new

button = JButton.new("Click Me")

listener = ActionListener.impl do
puts "button was clicked"
end

button.add_action_listener(listener)

panel.add(button)

frame.add(panel)
frame.pack()
frame.show()[/sourcecode]

click me



Similarities



  1. short and sweet, much nicer than writing this tiny thing in Java

  2. only one JVM specific call in both : importPackage and include_class respectively


Diffs



  1. Java support automatically 'on' in Rhino : no need to call something to initiate the Java support (JRuby: require 'java')

  2. Rhino has fewer lines : yes, part of this is how I include the classes, but not all...

  3. specifying the ActionListener : Rhino simply allows a function to be passed in... JRuby needs to have an impl of the ActionListener interface... which requires me to include that class

  4. speed : Rhino is faster for this silly test... this is most definitely due to the sheer size of the JRuby impl. Rhino comes in just about 3 times faster than JRuby.


Conclusion


Either way, it's much easier to work with than writing the same thing in Java. JRuby now has a few libraries to help you build your JRuby Swing apps:

I have not seen anything for Rhino, but that doesn't mean they don't exist!

No comments: