Sunday, December 17, 2006

Creating GUI with IronPython, Groovy and JRuby

I was curious what are the differences between the following tools when it comes to creating a GUI desktop application:
  • IronPython (with Windows Forms)
  • Groovy (with Swing)
  • JRuby (with Swing)

I prepared a simple example for each of them. The application shows a form with one button. This button when clicked changes its own text.

IronPython:

tested with 1.1a1 (1.1) on .NET 2.0.50727.42

  • Native windows
  • Possible to pass parameters in the constructor (form = Form(Text="test"))
  • Nice += for event handlers
  • As such a simple example it should work with Mono on Linux, however not sure about more complicated ones.

import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
from System.Windows.Forms
import Application, Button, Form
from System.Drawing import Size


form = Form(
Text="Hello",
Size=Size(200, 200)
)

button = Button(Text="OK!")

def onClick(event, handler):
button.Text = "Pressed!"

button.Click += onClick
form.Controls.Add(button)

Application.Run(form)


Groovy:
tested with 1.0-RC-01
(Thanks to Marcin Domański for his help on this example)
  • Cross-platform
  • Elegant event handlers api (actionPerformed:click)
  • Possible to pass parameters in the constructor (as in IronPython)


import javax.swing.JFrame
import javax.swing.JButton

def frame = new JFrame(
title:"Hello",
size:[200, 200],
defaultCloseOperation:JFrame.EXIT_ON_CLOSE
)

def click = {
event -> event.source.text = "Pressed!"
}

def button = new JButton(
text:"OK!",
actionPerformed:click
)

frame.add(button)
frame.show()



JRuby
tested with 0.9.2
  • Cross-platform
  • JRuby allows you to call Java code using the more Ruby-like underscore_method_naming and to refer to JavaBean properties as attributes.
  • Event handlers using classes is not nice


require 'java'
include_class "javax.swing.JFrame"
include_class "javax.swing.JButton"
include_class "java.awt.event.ActionListener"

frame = JFrame.new("Hello")
frame.set_size(200,200)
frame.defaultCloseOperation = JFrame::EXIT_ON_CLOSE

button = JButton.new("OK!")

class ClickListener < ActionListener
def actionPerformed(event)
event.source.text = "Pressed!"
end
end

button.add_action_listener(ClickListener.new)

frame.add(button)
frame.show


Update: There is a simpler Groovy version with SwingBuilder.

1 comment:

Alex Shneyderman said...

this post is on behalf of Martin C. Martin his suggested improvemnt over the Groovy version offered would be:
Click here to see original email

import groovy.swing.SwingBuilder

swing = new SwingBuilder()
frame = swing.frame(
title:"Hello",
size:[200, 200],
defaultCloseOperation:JFrame.EXIT_ON_CLOSE) {
button(
text:"OK!",
actionPerformed:{it.source.text = "Pressed!"})
}

frame.show()