import java.applet.*; import java.awt.*; public class MyBall extends Applet implements Runnable { Thread th; Ball ballA = new Ball(5, 10, 10, 1, 1, Color.BLUE); Ball ballB = new Ball(5, 10,190, 1,-1, Color.RED); Ball ballC = new Ball(5,190, 10,-1, 1, Color.GREEN); Ball ballD = new Ball(5,190,190,-1,-1, Color.BLACK);; public void start() { th = new Thread(this); th.start(); } public void run() { while (true) { repaint(); // paint() を呼び出す ballA.move(); ballB.move(); ballC.move(); ballD.move(); try { th.sleep(10); } catch(InterruptedException e) {} // 例外処理はしない } } public void paint(Graphics g) { ballA.display(g); // ballA の display メソッドを呼び出す ballB.display(g); ballC.display(g); ballD.display(g); } } // クラスの設計 class Ball { Color c; int size, x, y, xDelta, yDelta; Ball (int size, int x, int y, int xDelta, int yDelta, Color c) { this.size = size; this.x = x; this.y = y; this.xDelta = xDelta; this.yDelta = yDelta; this.c = c; } // メソッド public void move() { if (x + size >= 200) { xDelta = - xDelta; } if (y + size >= 200) { yDelta = - yDelta; } if (x < 0) { xDelta = (int) Math.round(Math.floor(Math.random()*20)); } if (y < 0) { yDelta = (int) Math.round(Math.floor(Math.random()*20)); } x = x + xDelta; y = y + yDelta; } public void display(Graphics g) { g.setColor(c); g.fillOval(x, y, size, size); }; }