Turning applications into applets
Many of you have used JyScript to make applications that you now
want to turn into applets. Here's an example that shows an easy way
to do it.
We earlier made an animation that moved a box across the screen.
Here is the code:
from JyScript import *
x = -1
def draw(p):
p.beginpage()
p.center()
p.scale(50)
p.box(x, -1, 2, 2)
p.fill(0, 0, 1)
p.stroke()
p.endpage()
def step():
global x
x += 0.02
refresh()
settimer(25, step)
def begin():
starttimer()
addbutton("Start", begin)
def pause():
stoptimer()
addbutton("Stop", pause)
def reset():
global x
stoptimer()
x = -1
refresh()
addbutton("Reset", reset)
openframe(200, 200, draw)
|
To make this into an applet, we won't need a frame anymore so
remove the openframe command.
#openframe(200, 200, draw)
|
Suppose that this code is in BoxAnimation.py. Define
an applet file BoxAnimationApplet, where we import
BoxAnimation, like this.
from JyScript import *
from javax.swing import *
import BoxAnimation
class BoxAnimationApplet(JApplet):
def __init__(self):
layoutapplet(200, 200, BoxAnimation.draw, self)
|
Remember that the name of the file must agree with the name of the
class so this file should be called
BoxAnimationApplet.py. You may test your applet by
including the command
testapplet(BoxAnimationApplet())
|
When it works well, remove the testapplet command and
build a jar file by typing this on the command line.
jythonc -j boxanimation.jar -c BoxAnimationApplet.py
|
Finally, construct your HTML tag:
<applet
code=BoxAnimationApplet
width=200
height=240
archive=boxanimation.jar>
</applet>
|
If your application has several panels called, say,
left and right, you may put them into the
applet with
layoutapplet([BoxAnimation.left, BoxAnimation.right], self)
|
|