Forum: JRuby JButton block.

Posted by Roger Pack (rogerdpack)
on 2010-11-18 22:52
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
Posted by Christian MICHON (Guest)
on 2010-11-18 23:04
(Received via mailing list)
On Thu, Nov 18, 2010 at 10:52 PM, Roger Pack <lists@ruby-forum.com> 
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
Posted by Ian Dees (Guest)
on 2010-11-19 00:45
(Received via mailing list)
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
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.