Google
 

Wednesday, May 16, 2007

Anonymous inner classes in Swing with JRuby

Yesterday I was tampering with Java Swing using JRuby, and doing stuff where I used ActionListener (duhh, being Swing and all..).

I found it quite annoying, that I couldn't seem to find a nice and easy way with JRuby, to declare anonymous inner classes for ActionListener classes on Swing components, using JRuby.

Luckily my ADSL modem turned off at 1am, and I was forced to either go to sleep or turn on the modem.

Today I searched for a nice solution. And I found this blog post:
http://blogs.dzone.com/daniel/2007/02/18/jruby-event-proxy/

which gives a great hint on how to use Ruby's elegant reflection to create a proxy_method. This proxy_method makes it easy to instantiate an interface (or class for that matter) and define how a method should be defined (or overridden). The content of the class is - not surprisingly - defined as a block for the proxy_method.

Notice the comments of the blog, where an alternative solution is suggested. This is actually the best, in my oppinion. The reason being that it seems much easier to get the actual ActionEvent instance, and call methods on that to enable stuff like:

listener = JProxy::ActionListener.new {
  def actionPerformed(e)
    puts "Clicked (#{e.actionCommand})!!"
  end
}

Nice..

technorati tags:, , , , ,

2 comments:

  1. See http://www.codecommit.com/blog/ruby/jruby-event-proxy for the original post.

    ReplyDelete

Please comment! I look forward into hearing your comments/oppinions.