Running Swing with JRuby

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

Wow!

The JRuby SwingRunner looks like:


# Import Java packages
include Java

import javax.swing.JFrame

frame = JFrame.new("Hello Swing")
button = javax.swing.JButton.new("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.
EOS
  end
end
button.add_action_listener(ClickAction.new)

# Add the button to the frame
frame.get_content_pane.add(button)

# Show frame
frame.set_default_close_operation(JFrame::EXIT_ON_CLOSE)
frame.pack
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.");
      }
    }
    );

    frame.getContentPane().add(button);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

  }
}

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!

Howdy!

Posted in java, jruby

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: