How to create a button class that uses blocks instead of listeners?

I’d like a JRuby button class that’s a subclass of the Swing button
class, but that allows one to say something like:

Rbutton.new(“Click me”) { puts “Clicked!” }

What I have so far is

require ‘java’

class Rbutton < javax.swing.JButton
def initialize(text)
super(text)
if block_given?
listener = java.awt.event.ActionListener.new
def listener.actionPerformed(event)
yield
end
self.addActionListener(listener)
end
end
end

frame = javax.swing.JFrame.new(“Window”)
label = Rbutton.new(“Hello”) {puts “Hello”}

frame.getContentPane.add(label)
frame.setDefaultCloseOperation(javax.swing.JFrame::EXIT_ON_CLOSE)
frame.pack
frame.setVisible(true)

The problem, of course, is that the yield is out of scope when it’s
called. Anyone know of a solution to this?

Thanks,
Ken McDonald


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email

require ‘java’

class Rbutton < javax.swing.JButton
def initialize(text)
super(text)
self.addActionListener Proc.new if block_given?
end
end

frame = javax.swing.JFrame.new(“Window”)
label = Rbutton.new(“Hello”) {puts “Hello”}

frame.getContentPane.add(label)
frame.setDefaultCloseOperation(javax.swing.JFrame::EXIT_ON_CLOSE)
frame.pack
frame.setVisible(true)

On Wed, Nov 26, 2008 at 10:45 AM, Kenneth McDonald
[email protected] wrote:

def initialize(text)

Thanks,
Ken McDonald


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email


Blog: http://www.bloglines.com/blog/ThomasEEnebo
Email: [email protected] , [email protected]


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email

Sweet! Thank you!

Ken

On Nov 26, 2008, at 10:55 AM, Thomas E Enebo wrote:

label = Rbutton.new(“Hello”) {puts “Hello”}

class,
super(text)
frame = javax.swing.JFrame.new(“Window”)


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email

Kenneth McDonald wrote:

The problem, of course, is that the yield is out of scope when it’s
called. Anyone know of a solution to this?
Capture the block with a closure.
class Rbutton < javax.swing.JButton
def initialize(text, &bl)
super(text)
if block_given?
self.addActionListener() {
bl.call
}
end
end
end


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email