Question

I am trying to play with JRuby with Java Swing : taking examples here and there, I am trying to translate them from pure Java to JRuby. That works well, especially after reading the part dedicated to Jruby in the excellent site Zetcode.

However there are things I still don't know how to translate.

For instance, picking this java code from Horstmann book, how could I translate correctly into JRuby ? In this code (in the Jpanel constructor), we rely on internal class for MouseAdapter. The rest is easy.

How to translate such internal (or more adequately 'anonymous') classes ?

Was it helpful?

Solution

just refactor/adjust parts to work out for you e.g.

frame = javax.swing.JFrame.new
frame.title = "MouseTest"
frame.set_size(300, 200)
frame.add_window_listener do |evt|
  if evt.getID == java.awt.event.WindowEvent::WINDOW_CLOSING
    java.lang.System.exit(0)
  end
end

class MousePanel < Java::JavaxSwing::JPanel

   SQUARELENGTH = 10; MAXNSQUARES = 100;

  def initialize
    super
    @squares = []; @current = nil
    add_mouse_listener self
    add_mouse_motion_listener self
  end

  def add(x, y)
    if @squares.size < MAXNSQUARES
       @current = @squares.size
       @squares << Point.new(x, y)
       repaint
    end
  end

  def remove(n)
    return if (n < 0 || n >= @squares.size)
    @squares.pop
    @squares[n] = @squares[@squares.size];
    @current = nil if @current == n
    repaint
  end

  def paintComponent(graphics)
    super
    @squares.each { |square| do_draw(graphics, square) }
  end

  def do_draw(graphics, square)
    graphics.drawRect(
      square.x - SQUARELENGTH / 2,
      square.y - SQUARELENGTH / 2,
      SQUARELENGTH, SQUARELENGTH
    )
  end
  private :do_draw

  include java.awt.event.MouseListener

  [ 'mouseEntered', 'mouseExited', 'mouseReleased' ].each do |method|
    class_eval "def #{method}(evt); end"
  end

  def mousePressed(evt)
    puts "mousePressed #{evt}"
  end

  def mouseClicked(evt)
    puts "mouseClicked #{evt}"
  end

  include java.awt.event.MouseMotionListener

  def mouseMoved(evt)
    puts "mouseMoved #{evt}"
  end

  def mouseDragged(evt)
    puts "mouseDragged #{evt}"
  end

end

frame.content_pane.add MousePanel.new
frame.show

NOTE all the updated *add_xxx_listener occurrences ...

put this into a gist for readability/forkability (including the original code) : https://gist.github.com/kares/8538048

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top