Compiling to an applet

An applet is a Java class that inherits from java.applet.Applet. The applet can be downloaded and run in a Java-capable web-browser. To generate an applet from a Scheme program, write the Scheme program with appropriate definitions of the functions ‘init’, ‘start’, ‘stop’ and ‘destroy’. You must declare these as zero-argument functions with a <void> return-type.

Here is an example, based on the scribble applet in Flanagan's "Java Examples in a Nutshell" (O'Reilly, 1997):

(define-private last-x 0)
(define-private last-y 0)

(define (init) <void>
  (let ((applet :: <java.applet.Applet> (this)))
    (invoke applet 'addMouseListener
	    (object (<java.awt.event.MouseAdapter>)
		    ((mousePressed (e :: <java.awt.event.MouseEvent>)) <void>
		     (set! last-x (invoke e 'getX))
		     (set! last-y (invoke e 'getY)))))
    (invoke applet 'addMouseMotionListener
	    (object (<java.awt.event.MouseMotionAdapter>)
		    ((mouseDragged (e :: <java.awt.event.MouseEvent>)) <void>
		     (let ((g :: <java.awt.Graphics>
			      (invoke applet 'getGraphics))
			   (x :: <int> (invoke e 'getX))
			   (y :: <int> (invoke e 'getY)))
		       (invoke g 'drawLine last-x last-y x y)
		       (set! last-x x)
		       (set! last-y y)))))))

(define (start) <void> (format #t "called start.~%~!"))
(define (stop) <void> (format #t "called stop.~%~!"))
(define (destroy) <void> (format #t "called destroy.~%~!"))

You compile the program with the ‘--applet’ flag in addition to the normal ‘-C’ flag:

java kawa.repl --applet -C scribble.scm

You can then create a ‘.jar’ archive containing your applet:

jar cf scribble.jar scribble*.class

Finally, you create an ‘.html’ page referencing your applet and its support jars:

<html><head><title>Scribble testapp</title></head>
<body><h1>Scribble testapp</h1>
You can scribble here:
<br>
<applet code="scribble.class" archive="scribble.jar, kawa-1.9.1.jar" width=200 height=200>
Sorry, Java is needed.</applet>
</body></html>

The problem with using Kawa to write applets is that the Kawa .jar file is quite big, and may take a while to download over a network connection. Some possible solutions: