Next: , Previous: , Up: Compiling   [Contents][Index]


6.5.5 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 (this)))
    (applet:addMouseListener
     (object (java.awt.event.MouseAdapter)
	     ((mousePressed e)
	      (set! last-x (e:getX))
	      (set! last-y (e:getY)))))
    (applet:addMouseMotionListener
     (object (java.awt.event.MouseMotionAdapter)
	     ((mouseDragged e)
	      (let ((g (applet:getGraphics))
		    (x (e:getX))
		    (y (e:getY)))
		(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-2.93.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:


Next: , Previous: , Up: Compiling   [Contents][Index]