Category Archives: JavaScript

Simple JavaScript Console

Here are more details on the console thingy seen in my post about scripting, it’s nothing terribly special, just a simple UI with a few extras like redirecting System.out/err to the output area in the frame, download the code below and take a look.

Here is how you use it:

public class ConsoleDemo extends Scene2D {
private ImageSprite man, spirit;

public void load() {
add(new FilledSprite(Colors.WHITE));

man = new ImageSprite("Man.png", 10, 10);
spirit = new ImageSprite("Spirit.png", 100, 10);

ConsoleFrame consoleFrame = new ConsoleFrame();

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
scriptEngine.put("demo", this);

consoleFrame.setLocation(900, 200);

public ImageSprite getMan() {
return man;

public void setMan(ImageSprite man) { = man;

public ImageSprite getSpirit() {
return spirit;

public void setSpirit(ImageSprite spirit) {
this.spirit = spirit;

Just make sure you instantiate the ConsoleFrame before the ScriptEngineManager or the System.out/err redirection will not work. Also, the example is PulpCore based but there is no PulpCore dependency in the ConsoleFrame code.

And now a trivial script:


Putting an instance in the scripting engine like this scriptEngine.put("demo", demoInstance) makes it available with that name, members that are public or have getters/setters are directly accessible from JavaScript.

And one somewhat important caveat, the Swing code runs in it’s own thread and so does the scripting engine, changing the game state from a script can lead to inconsistencies at times if your code is not thread safe (and likely it is not – usually games are coded single-threaded), to avoid problems first pause the game loop, run the script and make your changes and then resume the loop. For PulpCore you can do this by calling Scene2D.setPaused()

More details and documentation on scripting Java classes at, especially this

Download the source code.