public
Last active

example code of how to do an "on_click" method for a JButton

  • Download Gist
easy_way.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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
even_easier_way.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.