如何在JRuby代码中翻译Java内部类的使用

时间:2014-01-20 22:37:12

标签: jruby

我正在尝试使用Java Swing使用JRuby:在这里和那里举例,我试图将它们从纯Java转换为JRuby。这很有效,特别是在优秀的网站Zetcode中阅读了专注于Jruby的部分之后。

然而,有些事情我仍然不知道如何翻译。

例如,选择this java code from Horstmann book,我怎样才能正确地翻译成JRuby?在这段代码中(在Jpanel构造函数中),我们依赖于MouseAdapter的内部类。其余的很容易。

如何翻译这些内部(或更充分'匿名')的课程?

1 个答案:

答案 0 :(得分:0)

只需重构/调整部件就可以解决问题,例如

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

注意所有更新的* add_xxx_listener次数......

将其放入可读性/可分解性的要点(包括原始代码):https://gist.github.com/kares/8538048