Search code examples
javajrubycode-translationjmonkeyengine

Translate JMonkey Tutorial to JRuby


I've got all the tutorials up to beginner #5 translated and working, but I don't know Java well enough to know how to port the lines:

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) {
    ...
  }
}

How might this work?


Solution

  • Ah, found the answer. Turns out, they were anonymous inner classes. In JRuby, you can just create a class that implements the Java interface like so:

    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