Running Swing with JRuby

Inside $JRUBY_HOME there are some samples. One is running a simple Swing application w/ JRuby.


The JRuby SwingRunner looks like:

# Import Java packages
include Java

import javax.swing.JFrame

frame ="Hello Swing")
button ="Klick Me!")

class ClickAction
  include java.awt.event.ActionListener
  def actionPerformed(evt)
    javax.swing.JOptionPane.showMessageDialog(nil, <<EOS)
<html>Hello from <b><u>JRuby</u></b>.<br>
Button '#{evt.getActionCommand()}' clicked.

# Add the button to the frame

# Show frame
frame.visible = true

Sure, that looks different, when coming (like I) from a kind of Java-only perspective. Some keywords are different or used in a different way, like the new operator or how to access a constant. But, after I read it once more, I start to like it.I “ported” it over to real Java 🙂 to show the difference:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class SwingRunner {

  public static void main(String[] args)
    JFrame frame = new JFrame("Hello Swing");
    JButton button = new JButton("Klick Me!");

    button.addActionListener(new ActionListener()
      public void actionPerformed(ActionEvent evt)
        JOptionPane.showMessageDialog(null, "<html>Hello from <b><u>Java</u></b>.<br> Button " + evt.getActionCommand() + " clicked.");




I think that is a little bit more typing. But perhaps you haven’t noticed, but the JRuby version supports Expressions 🙂 Like #{evt.getActionCommand()}. Cool!
Sure! This little (stupid) demo doesn’t sell (J)Ruby at all, but to me it was interesting and I think an eyeopener. Since I prefer reading books (perhaps I am traveling too much) I ordered Ola’s Book on JRuby and Rails.I need more of that!



Posted in java, jruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: