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


#1

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

#2

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
removed_email_address@domain.invalid 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: removed_email_address@domain.invalid , removed_email_address@domain.invalid


To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email

#3

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

#4

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