将JMonkey教程翻译成JRuby

时间:2012-03-22 20:16:57

标签: java jruby code-translation jmonkeyengine

我已经完成了所有教程的初学者#5翻译和工作,但我不太了解Java,知道如何移植这些行:

private ActionListener actionListener = new ActionListener() {
  public void onAction(String name, boolean keyPressed, float tpf) {
    if (name.equals("Pause") && !keyPressed) {
      isRunning = !isRunning;
    }
  }
};

private AnalogListener analogListener = new AnalogListener() {
  public void onAnalog(String name, float value, float tpf) {
    ...
  }
}

这怎么可能有用?

3 个答案:

答案 0 :(得分:1)

Calling Java from JRuby中所述,您可以使用闭包转换,其中块可用于定义Java接口行为。以下内容应该有效:

l = lambda { |name, pressed, tpf| running = !running if name == 'Pause' && !pressed }
input_managers.add_listener(l, ['Left', 'Right', 'Rotate'])

答案 1 :(得分:0)

啊,找到了答案。事实证明,他们是匿名的内部阶级。在JRuby中,您可以创建一个实现Java接口的类,如下所示:

class RBActionListener
  # This is how you implement Java interfaces from JRuby
  include com.jme3.input.controls.ActionListener

  def initialize(&on_action)
    @on_action = on_action
  end

  def onAction(*args)
    @on_action.call(*args)
  end
end

class HelloJME3
  # blah blah blah code blah blah blah

  def register_keys
    # ...
    ac = RBActionListener.new {|name, pressed, tpf @running = !@running if name == "Pause" and !pressed}
    input_manager.add_listener(ac, "Pause")
  end
end

答案 2 :(得分:0)

我将动作侦听器包装在一个方法中,该方法将返回一个包含ActionListener的对象,使用JRuby的:impl方法

def isRunningActionListener
  return ActionListener.impl do
    |command, name, keyPressed, tpf|
      case command
        when :onAction
          if name.eql?("Pause") && !keyPressed
            isRunning = !isRunning;
          end
      end
   end
end

您还可以创建自己的ActionListener类,其中包含ActionListener ...

class YourActionListener
  include ActionListener
  def onAction command, name, keyPressed, tpf
    #your code here
  end
end

创建自己的类可能是更好的选择,因为它更简洁,更易于阅读和理解。