Posts Tagged ‘java’

Ruby-GTK behavior in JRuby-GTK (using Java’s GTK)

Friday, June 25th, 2010

When I first started playing around with JRuby, I quickly found out, that the GTK-extension for Ruby did not work with JRuby, since it was a native C-extension, which could not be loaded into Java.

To load GTK in JRuby anyway, I had to install the Java GTK on my Ubuntu machine. This is pretty easy – just fire off a “sudo aptitude install libjava-gnome-java” and your done…

Java’s GTK is a lot different from the Ruby version. First of all a lot of the Ruby-objects has optimized constructors. You can construct a window with a title by doing:

window = Gtk::Window.new("The title")

In Java this is not possible, so if you give the argument your app fails. This meant that JRuby wasnt able to handle some of my GTK-apps. I then decided to write a kind of wrapper, which would emulate the behavior of the Ruby-GTK in JRuby-GTK (Java’s GTK). This turned out to be a lot harder than I first thought.

First off I had to make dynamic events-classes for the connect-method, to first do it the Java-way and then call blocks in Ruby to turn it into the Ruby way – which I had never done before.

All in all I was able to get the following examples to work in JRuby with Java’s GTK loaded:

require "knj/jruby-gtk2/gtk2.rb"
require "knj/jruby-gtk2/gladexml.rb"

class WinAppEdit
	def initialize
		@glade = GladeXML.new("win_app_edit.glade"){|h|method(h)}
		@glade["window"].show_all
	end

	def on_btnSave_clicked
		print "Save clicked.\n"
	end

	def on_btnCancel_clicked
		print "Cancel clicked.\n"
	end

	def on_window_destroy
		print "Destroyed!\n"
		Gtk.main_quit
	end
end

WinAppEdit.new

Gtk.main

And the normal one:

require "knj/jruby-gtk2/gtk2.rb"

button = Gtk::Button.new("Test")
button.connect("clicked") do
	print "Clicked!\n"
end

win = Gtk::Window.new("Trala")
win.add(button)
win.show_all

win.connect("destroy") do
	print "Destroy!\n"
	Gtk.main_quit
end

Gtk.main

Why go through all of this, just so my Ruby-GTK applications can run through JRuby? Scalability, real threads, packaged Java-apps and so on…

The whole thing can be checked out at my account on GitHub:

http://github.com/kaspernj/knjrbfw

http://github.com/kaspernj/knjrbfw/blob/master/jruby-gtk2/gtk2.rb

http://github.com/kaspernj/knjrbfw/blob/master/jruby-gtk2/gladexml.rb

Be warned that this project is far from done – its actually more a proof of concept for myself :-)