レッスン4

レッスン3は環境によっては画面がちらつくかもしれません。 今度はどうでしょうか。 ダブルバッファリングという手法を使ってみました。


import java.awt.*;
import java.applet.Applet;

public class Lesson4 extends Applet implements Runnable {
    int x, y, dx = 10, dy = 10, w, h;
    Thread ball;
    Image buf;
    Graphics gr;

    public void init() {
        w = getWidth();
        h = getHeight();
        x = w / 2;
        y = h / 2;
        buf = createImage(w, h);
        gr = buf.getGraphics();
    }

    public void start() {
        if (ball == null) {
            ball = new Thread(this);
            ball.start();
        }
    }

    public void stop() {
        ball = null;
    }

    public void update(Graphics g) {
        g.drawImage(buf, 0, 0, this);
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (ball == thisThread) {
            try {
                thisThread.sleep(100);  // sleep 100msec
            } catch (InterruptedException e) {
            }
            if (x <= 10 || x >= w  - 10) dx = -dx;
            if (y <= 10 || y >= h - 10) dy = -dy;
            x += dx;  y += dy;
            gr.setColor(Color.white);
            gr.fillRect(0, 0, w, h);
            gr.setColor(Color.blue);
            gr.fillOval(x - 10, y - 10, 20, 20);
            repaint();
        }
    }
}

奥村晴彦

Last modified: 2005-12-29 10:59:02