アニメーション

Image image1;
image1 = createImage(getSize().width, getSize().height);
createImage(getSize().width, getSize().height); で、ウインドウのサイズ分の領域を確保します。ここで、getSize()
はウインドウのサイズを取得するメソッドで、.width がその幅、.height が高さになります。
Graphics offgraphics;
offgraphics = image1.getGraphics();
この offgraphics に
offgraphics.fillOval( )
のように、描画をすることができます。この時点ではまだ、画面には現れません。描画内容は Imaeg1 に記録されています。すべての描画が終了したら、
g.drawImage(image1, 0, 0, this);
で、Image1を g の画面に描画します。この速度はかなり高速ですから、この間にディスプレイが消去を行う危険性は軽減されます。
Thread thread1;
thread1 = new Thread(this);
thread1.start();
でスレッドを作成し、run()による実行を開始します。ここでは、repaint() と、10m秒 sleep() を繰り返します。 public void run() {
while (true) {
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
paint()では、loop_index の値を増加させながら、黒の塗りつぶし楕円を描画します。黒の塗りつぶしをすると、背景を白にする消去を見やすくなり、「ちらつき」が観測できます。 public void update(Graphics g) {
paint(g);
}
ただし、バッファの消去は必要ですから、paint() の中で、graphics.clearRect(0, 0, getSize().width, getSize().height);で、バッファをクリアします。ダブルバッファを利用しない場合、これは不要ですが、update(Graphics g) の書き換えをしてはいけません。
if (checkbox.getState()) graphics = offgraphics;で、チェックを確認し、graphics を切り替えています。また、同じ条件で、最後に、 g.drawImage(image1, 0, 0, this);
import java.awt.*;
import java.applet.*;
public class anima extends Applet implements Runnable {
Image image1;
Graphics offgraphics;
Thread thread1;
int loop_index = 0;
Checkbox checkbox = new Checkbox();
public void init() {
checkbox.setLabel("DoubleBuffer");
checkbox.setBounds(new Rectangle(20, 220, 60, 20));
this.setLayout(null);
this.add(checkbox, null);
}
public void start() {
image1 = createImage(getSize().width, getSize().height);
offgraphics = image1.getGraphics();
//System.out.println("image size="+image1.getWidth(this));
thread1 = new Thread(this);
thread1.start();
}
public void run() {
while (true) {
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
Graphics graphics = g;
if (checkbox.getState())
graphics = offgraphics;
graphics.clearRect(0, 0, getSize().width, getSize().height);
Color c1 = new Color(100, 100, 100);
Color c2 = new Color(10, 50, 50);
loop_index += 2;
if (loop_index >= 200)
loop_index = 5;
graphics.setColor(c1);
graphics.fillOval(
100 - loop_index / 2,
100 - loop_index / 2,
loop_index,
loop_index);
graphics.setColor(c2);
if (checkbox.getState())
g.drawImage(image1, 0, 0, this);
}
}