Andy has posted 1 posts at DZone. View Full User Profile

Glimmer - Using Ruby to Build SWT User Interfaces

  • submit to reddit

Another example that benefits from event monitoring is field validation on loss of focus. For example, let's say we are validating the ZIP code on an address form, and we would like to display an error message if its value does not have a valid ZIP code format (e.g. 12345 or 12345-1234,) here is how we would do it with Glimmer (please add the following code before the button in the previous example):

import org.eclipse.swt.widgets.MessageBox

@shell1 = shell {
  composite {
    label { text "ZIP Code" }
    text {
      on_focus_lost { |focus_event|
        zip_code = focus_event.widget.text
        unless zip_code =~ /^\d{5}([-]\d{4})?$/
          message_box =, SWT::NULL)
          message_box.text = 'Validation Error'
          message_box.message = 'Format must match ##### or #####-####'

    button {
      text 'Save'
      on_widget_selected {
        message_box =, SWT::NULL)
        message_box.message = 'Saved!'

Here is what it produces:

Notice how the on_focus_lost block has a FocusEvent object as a parameter. This parameter may be specified optionally whenever some information is needed from the event object.

Again, this maps to the focusLost method on the FocusListener class in the original SWT API, which also takes a FocusEvent object as a parameter.

While widgets in the original SWT API have a setFocus event to grab the user interface focus, in JRuby set_focus may be used instead following the Ruby naming conventions.

Now, in order to cleanly separate event-driven behavior from user-interface code, we can rely on Glimmer's data-binding support. Stay tuned for the next tutorial, which will cover data-binding and how to achieve clean code separation with the Model-View-Presenter pattern.


Glimmer Eclipse Technology Project Proposal:

Glimmer Newsgroup:

Glimmer at RubyForge:

Author Blog:

Andy Maleh (andy at, Senior Consultant, Obtiva Corp.

Published at DZone with permission of its author, Andy Maleh.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)