Homework 1, due Monday, Sept 17.

When you have finished the assignment below, post the working applet onto the web.

I've provided a very simple Applet which conforms to the Java 1.1 spec, below, for the benefit of those of you who've never written a Java applet before. If you don't have a Java development kit already, you can fetch one at http://java.sun.com/products/jdk/1.1/.

I tried to err on the side of simplicity, to make it easy for you to get started, but I implemented double-buffering for you, so you won't get annoying flicker in your applets. All my applet does is let you drag the mouse around to move a big 'X' shape. You can compile it with: javac MySimpleApplet.java and you can run it by loading file MySimpleApplet.html in your Web browser.

Your assignment for this week is very simple. Just get this applet running, post it to your web page, and change the figure 'X' to a figure 'Y'.




MySimpleApplet.html

<html> <head> <title>MySimpleApplet</title> </head> <body> <applet code=MySimpleApplet.class width=400 height=400> </applet> </body> </html>

MySimpleApplet.java

import java.awt.*; public class MySimpleApplet extends GenericApplet { int x = 100, y = 100; public void render(Graphics g) { if (damage) { g.setColor(Color.white); g.fillRect(0, 0, bounds().width, bounds().height); g.setColor(Color.black); g.drawLine(x - 20, y + 20, x + 20, y - 20); g.drawLine(x - 20, y - 20, x + 20, y + 20); } } public boolean mouseDown(Event e, int x, int y) { moveXY(x, y); return true; } public boolean mouseDrag(Event e, int x, int y) { moveXY(x, y); return true; } void moveXY(int x, int y) { this.x = x; this.y = y; damage = true; } } class GenericApplet extends java.applet.Applet implements Runnable { public boolean damage = true; // you can force a render public void render(Graphics g) { } // you can define how to render private Image image = null; private Graphics buffer = null; private Thread t; private Rectangle r = new Rectangle(0, 0, 0, 0); public void start() { if (t == null) { t = new Thread(this); t.start(); } } public void stop() { if (t != null) { t.stop(); t = null; } } public void run() { try { while (true) { repaint(); t.sleep(30); } } catch(InterruptedException e){}; } public void update(Graphics g) { if (r.width != bounds().width || r.height != bounds().height) { image = createImage(bounds().width, bounds().height); buffer = image.getGraphics(); r = bounds(); damage = true; } render(buffer); damage = false; if (image != null) g.drawImage(image,0,0,this); } }