import java.awt.*; // AWT(AbstractWindowingToolkit):Graphics用 import javax.swing.*; // Window, GUI: JPanel, JFrame用 public class Ex11_2 extends JPanel implements Runnable { int x,y,dia,t; double theta; Thread thd = null; // スレッド public Ex11_2() { // コンストラクタ setOpaque(false); // 前絵を消してから描画する設定 x = 10; y = 10; dia = 50; // 初期位置(x,y), 直径dia t = 0; // 時間t theta = Math.PI/12; // 角度θ(=π/12ラジアン = 15度) thd = new Thread(this); thd.start(); // スレッド開始 } public void paintComponent(Graphics g) { // 描画用メソッド if (x % 3 == 0) { g.setColor(Color.BLUE); g.fillOval(x,y,dia,dia); } else if (x % 3 == 1) { g.setColor(Color.RED); g.fillRect(x,y,dia,dia); } else { g.setColor(Color.GREEN); g.fillRoundRect(x,y,dia,dia,5,5); } g.setColor(Color.BLACK); g.drawString("("+String.valueOf(x)+","+String.valueOf(y)+")", 10, 10); } public static void main(String[] args) { // mainメソッド JFrame app = new JFrame(); app.add(new Ex11_2()); app.setTitle("3色図形アニメ"); app.setSize(300, 200); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setVisible(true); } public void run() { // アニメーション用メソッド while (true) { x = (x + 2) % 300; // x座標の位置を変更 y = y + (int)(15 * Math.sin(theta*t)); // y座標の位置を変更 t++; // 時間 t = t + 1 repaint(); // 再描画(paintComponent()呼び出し) try { thd.sleep(200); // スレッド停止時間(200ミリ秒) } catch (InterruptedException e) { e.printStackTrace(); // スタックトレースを出力 } } } }