Translate JMonkey tutorial to JRuby
I have all the pre-newbie # 5 tutorials translated and working, but I don't know Java well enough to know how to line break:
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 it works?
source to share
Ah, I found the answer. It turns out they were anonymous inner classes. In JRuby, you can simply create a class that implements the Java interface like this:
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
source to share
As described in Calling Java from JRuby , you can use a closure transformation, where blocks can be used to define the behavior of a Java interface. Something like the following should work:
l = lambda { |name, pressed, tpf| running = !running if name == 'Pause' && !pressed }
input_managers.add_listener(l, ['Left', 'Right', 'Rotate'])
source to share
I wrapped an action listener in a method that returns an object that includes an ActionListener using the JRuby: impl method
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
you can also create your own ActionListener class that includes an ActionListener ...
class YourActionListener
include ActionListener
def onAction command, name, keyPressed, tpf
#your code here
end
end
creating your own class might be a better option as it is much less detailed and easier to read and understand.
source to share