Skip to content

Instantly share code, notes, and snippets.

@rdp
Created November 18, 2010 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdp/705822 to your computer and use it in GitHub Desktop.
Save rdp/705822 to your computer and use it in GitHub Desktop.
example code of how to do an "on_click" method for a JButton
require 'java'
include_class 'javax.swing.JButton'
include_class 'javax.swing.JFrame'
include_class 'javax.swing.JLabel'
include_class 'java.awt.event.ActionListener'
class ClickAction
include ActionListener
def initialize &block
@block = block
raise unless block_given?
end
def actionPerformed(event)
@block.call
end
end
class JButton
def on_clicked &block
# maybe it can only have one on click handler for now?
handler = ClickAction.new &block
add_action_listener handler
end
end
class MainWindow < JFrame
def initialize
super "JRuby/Swing Demo"
button = JButton.new( "Click me!")
button.on_clicked {
p 'clicked good'
}
add button
pack
end
end
MainWindow.new.show
require 'java'
include_class 'javax.swing.JButton'
include_class 'javax.swing.JFrame'
include_class 'javax.swing.JLabel'
include_class 'java.awt.event.ActionListener'
class JButton
def on_clicked &block
# maybe it can only have one on click handler for now?
add_action_listener do |e|
block.call
end
end
end
class MainWindow < JFrame
def initialize
super "JRuby/Swing Demo"
button = JButton.new( "Click me!")
button.on_clicked {
p 'clicked good'
}
add button
pack
end
end
MainWindow.new.show
@rdp
Copy link
Author

rdp commented Nov 19, 2010

"even easier way" gleaned from http://www.ruby-forum.com/topic/479162#962470

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment