jruby/docs BETA
SWT · intro

Build a tabbed editor in 50 lines of JRuby

8 min read

Build a tabbed editor in 50 lines of JRuby

Here is a minimal tabbed text editor you can paste and run.

The code

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'swt', github: 'marcheiligers/swt', branch: '4_39'
end

require 'swt'

include Swt
include Swt::Widgets
include Swt::Custom
include Swt::Layout

display = Display.new
shell   = Shell.new(display)
shell.text = 'Tabbed Editor'
shell.layout = FillLayout.new

folder = CTabFolder.new(shell, SWT::BORDER | SWT::CLOSE)
folder.simple = false

def add_tab(folder, label, content = '')
  item = CTabItem.new(folder, SWT::NONE)
  item.text = label
  text = StyledText.new(folder, SWT::MULTI | SWT::WRAP | SWT::V_SCROLL)
  text.text = content
  item.control = text
  item
end

add_tab(folder, 'README.md', "# My Project\n\nEdit me.")
add_tab(folder, 'Untitled 1')
folder.selection = 0

# New tab on double-click of the tab bar
folder.add_listener(SWT::MouseDoubleClick) do |_e|
  n = folder.item_count + 1
  add_tab(folder, "Untitled #{n}")
  folder.selection = folder.item_count - 1
end

shell.set_size(800, 600)
shell.open

until shell.disposed?
  display.sleep unless display.read_and_dispatch
end

display.dispose

Running

ruby -J-XstartOnFirstThread tabbed-editor.rb

How it works

  • I maintain a fork of the SWT gem updated to a more recent SWT release, which we bundle using bundler/inline
  • Shell is the Window. We give it a FillLayout
  • CTabFolder is the tab control and SWT::CLOSE adds a close button to every tab
  • StyledText is the editor which supports rich text
  • The double-click listener on the folder opens a new blank tab.
    SWT fires mouseDoubleClick on the folder (not the item) when clicking
    the empty strip to the right of the last tab.

Next steps

  • Add a CTabFolder2Adapter to intercept the close button and show a “save
    changes?” dialog before removing the tab.
  • Wire up FileDialog to add_tab so users can open files.
  • Add a ToolBar with rich text controls like bold, italics and underline.
← All recipes