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!

1 comment:

Unknown said...

How to get to the casino at the casino: 12 Steps | Tricktactoe
1. Go to the main game 장원 주소 page. 2. 토토 마켓 Go to the main 스포츠토토 구입 샤오미 page. 3. Click on "Login" in the upper right 스포츠토토 확률 샤오미 corner. 4. Click on the 프로토 토토 승부 식 큐어 벳 button "Login".