import java.awt.*; // AWT(AbstractWindowingToolkit): Graphics import java.awt.image.*; // BufferedImage など import java.io.*; // File など import javax.swing.*; // Window, GUI: JPanel, JFrame import javax.imageio.*; // ImageIO public class Ex11_3 extends JPanel implements Runnable { int x1, y1, x2, y2, x3, y3, t; BufferedImage img1 = null; // 画像1用 BufferedImage img2 = null; // 画像2用 BufferedImage img3 = null; // 画像3用 Thread thd = null; // スレッド public Ex11_3() { // コンストラクタ setOpaque(false); // 前絵を消してから描画する設定 try { img1 = ImageIO.read(new File("img/nyan2.gif")); // 画像の読み込み img2 = ImageIO.read(new File("img/teku2.gif")); // 画像の読み込み img3 = ImageIO.read(new File("img/drive3.gif")); // 画像の読み込み } catch (Exception e) { e.printStackTrace(); } x1 = 10; y1 = 100; // img1: 初期位置(x1,y1) x2 = 200; y2 = 100; // img2: 初期位置(x2,y2) x3 = 10; y3 = 10; // img3: 初期位置(x3,y3) t = 0; // 時間t thd = new Thread(this); thd.start(); // スレッド開始 } public void paintComponent(Graphics g) { // 描画用メソッド g.drawImage(img1, x1, y1, this); // 図形1(img1)描画 g.drawImage(img2, x2, y2, this); // 図形2(img2)描画 g.drawImage(img3, x3, y3, this); // 図形2(img3)描画 } public static void main(String[] args) { // mainメソッド JFrame app = new JFrame(); app.add(new Ex11_3()); app.setTitle("アニメ"); app.setSize(300, 200); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setVisible(true); } public void run() { // アニメーション用メソッド while (t<200) { // img1が近づく… x2 -= 1; // x2座標の位置を変更 t++; // 時間 t = t + 1 repaint(); // 再描画(paintComponent()呼び出し) try { thd.sleep(50); // スレッド停止時間(200ミリ秒) } catch (InterruptedException e) { e.printStackTrace(); // スタックトレースを出力 } } while (t<250) { // img2が逃げる… y1 -= 2; // y1座標の位置を変更 t++; // 時間 t = t + 1 repaint(); // 再描画(paintComponent()呼び出し) try { thd.sleep(10); // スレッド停止時間(200ミリ秒) } catch (InterruptedException e) { e.printStackTrace(); // スタックトレースを出力 } } while (t<300) { // img3がはなれる… x3 += 5; // x3座標の位置を変更 t++; // 時間 t = t + 1 repaint(); // 再描画(paintComponent()呼び出し) try { thd.sleep(10); // スレッド停止時間(200ミリ秒) } catch (InterruptedException e) { e.printStackTrace(); // スタックトレースを出力 } } } }