Rhino uses the jvm to allow javascript to be embedded into java and for javascript to gain access to all those libraries java has. Much like using C to write extensions to PHP you can now use Java to write extensions to javascript. But in the interest of a Javascripter like me. I am just happy using the pure javascript. The source below is converted from java example, except its now in Javascript.
var awt = java.awt;
var event = awt.event;
var graphics = awt.Graphics;
var system = java.lang.System;
var smileyCanvas = new JavaAdapter(awt.Canvas, {
paint: function (g) {
var size = this.getSize();
var d = Math.min(size.width, size.height);
var ed = d / 20;
var x = (size.width - d) / 2;
var y = (size.height - d) / 2;
// draw head (color already set to foreground)
g.fillOval(x, y, d, d);
g.setColor(awt.Color.black);
g.drawOval(x, y, d, d);
// draw eyes
g.fillOval(x+d/3-(ed/2), y+d/3-(ed/2), ed, ed);
g.fillOval(x+(2*(d/3))-(ed/2), y+d/3-(ed/2), ed, ed);
//draw mouth
g.drawArc(x+d/4, y+2*(d/5), d/2, d/3, 0, -180);
}
});
smileyCanvas.setForeground(awt.Color.yellow);
var winAdapter = new JavaAdapter(event.WindowAdapter, {
windowClosing: function (evt) {
system.exit(0);
}
});
var f = new awt.Frame('Have a nice day');
f.addWindowListener(winAdapter);
f.add(smileyCanvas, awt.BorderLayout.CENTER);
f.pack();
f.show();
f.setSize(new awt.Dimension(320, 240));
>> cd C:\where-my-work-is\
>> java -cp js.jar org.mozilla.javascript.tools.shell.Main smiley.js;
// mylib.js
var hello = function () {
print('hi');
};
//Sample.js
load('mylib.js') // Single File
hello();
importPackage(java.awt);
var myColor = new Color(0.5, 0.5, 0.0);
// What are the rgb's ?
print(myColor);
// Let extend this
myColor.foo = function () {
print('bar');
}
// ERROR Java class "java.awt.Color" has no public instance field or method named "foo"
importPackage(java.awt);
var object = JavaAdapter(java.lang.Object);
// Let extend this
object.value = []
object.toString = function () {
return this.values.join(', ');;
};
// or
var object = new JavaAdapter(Color, java.lang.Object, {
values: [],
toString: function () {
return this.values.join(', ');
}
});
function JMArrayObject(arrayValues) {
// the same as calling super()
var object = JavaAdapter(java.lang.Object, {
values: null,
toString: function () {
return this.values.join(', ');
}
});
// Do your constructor stuff here
object.values = arrayValues;
// return the object
return object;
}
var ao = new JMArrayObject([0.75,0.5,0.5]);
print(ao);
// Output: 0.75, 0.5, 0.5
jar -xf js.jar
java org.mozilla.javascript.tools.jsc.Main -nosource -opt 9 -version 170 smiley.js;
-nosource removes the javascript source code to reduce filesize, -opt 9 sets maximum performance, and -version 170 just means use javascript 1.7
smiley
Note the extra line space in the file and whats above its needed. Also note that what ever you name your main javascript mush be used as the name above (case sensitive).
jar cmf smiley.txt smiley.jar *