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
Shellis the Window. We give it aFillLayoutCTabFolderis the tab control andSWT::CLOSEadds a close button to every tabStyledTextis the editor which supports rich text- The double-click listener on the folder opens a new blank tab.
SWT firesmouseDoubleClickon the folder (not the item) when clicking
the empty strip to the right of the last tab.
Next steps
- Add a
CTabFolder2Adapterto intercept the close button and show a “save
changes?” dialog before removing the tab. - Wire up
FileDialogtoadd_tabso users can open files. - Add a
ToolBarwith rich text controls like bold, italics and underline.