JButton block

With this code [1]:

I get “input” to a JButton that looks like

[#Java::JavaxSwing::JButton:0x8b1a4f,
#Java::SunJava2d::SunGraphics2D:0xfb6c5f, 30, 13]

But never (from what I can tell), anything that looks like a “button was
clicked” message.
Is this expected? Does anyone know of an easier way to add “on_click”
listeners and such?

Thanks!
-r

[1]
require ‘java’

include_class ‘java.awt.event.ActionListener’
include_class ‘javax.swing.JButton’
include_class ‘javax.swing.JFrame’

class ClickAction
include ActionListener

def actionPerformed(event)
puts “Button got clicked.”
end
end

class MainWindow < JFrame
def initialize
super “JRuby/Swing Demo”
setDefaultCloseOperation JFrame::EXIT_ON_CLOSE

 button = JButton.new( "Click me!") do |e|
   p e
  end
 button.addActionListener ClickAction.new
 add button
 pack

end
end

MainWindow.new.setVisible true

On Thu, Nov 18, 2010 at 10:52 PM, Roger P. [email protected]
wrote:

listeners and such?

I would code it like this, using the ‘getActionCommand’ trick (biggest
drawback: the method’s name must match the button’s label)

require ‘java’
include_class ‘java.awt.event.ActionListener’
include_class ‘javax.swing.JButton’
include_class ‘javax.swing.JFrame’
class MainWindow < JFrame
include ActionListener
def initialize
super “JRuby/Swing Demo”
setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
button = JButton.new(“click_me”)
button.addActionListener self
add button
pack
end
def actionPerformed(ev)
send ev.getActionCommand
end
def click_me
puts “Button got clicked.”
end
end
MainWindow.new.setVisible true

Regards,

Christian

Hi, Roger.

Does anyone know of an easier way to add “on_click”
listeners and such?

You can pass a block to addEventListener, like so:

button = JButton.new("Click me!")
button.addActionListener do |e|
  puts "Button got clicked."
end

–Ian