www.delorie.com/gnu/docs/kawa/kawa_23.html   search  
Buy GNU books!

Kawa, the Java-based Scheme system

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4 Compiling Scheme 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. You also need to include the Kawa classes in the `.jar', or you can include a MANIFEST file that specifies Class-Path to use a Java 2 download extension.
jar cf scribble.jar scribble*.class other-classes ...

Finally, you create an `.html' page referencing your applet:
<html><head><title>Scribble testapp</title></head>
<body><h1>Scribble testapp</h1>
You can scribble here:
<applet code="scribble.class" archive="scribble.jar" width=200 height=200>
Sorry, Java is needed.</applet>

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003