Created
November 18, 2010 22:44
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"even easier way" gleaned from http://www.ruby-forum.com/topic/479162#962470