2つの変更をします。
1.一つ前の円を消して軌跡を残さない
2.右端までいったら左へ進むようにし、左端へいったら右へ進むようにする
MoveDisk2.javaをもとに、スレッドを使う moveDisk の部分だけ変わります。
//円を動かすクラス class moveDisk extends Thread{ MyPanel pnl; BufferedImage image; int x = 100; int y ; int lx =0; int d = 10; int dx = 10; //constructor public moveDisk(MyPanel pn, BufferedImage im) { this.pnl = pn; this.image = im; y = (int)(image.getHeight()*Math.random()); } @Override public void run() { Graphics thg = image.createGraphics(); Color bc= new Color(255,255,191); //背景の色 thg.setColor(Color.red); thg.drawString(getName(),x-90,y); while ( true ){ thg.setColor(bc); thg.fillOval(lx-d/2,y-d/2,d,d); thg.setColor(Color.red); thg.fillOval(x-d/2,y-d/2,d,d); pnl.repaint(); lx = x; x += dx; if (x >image.getWidth()){ x = 2*image.getWidth()-x; dx = -dx; } if (0 > x){ x = -x; dx = -dx; } //100ms(0.1秒)停止 try { Thread.sleep(100); } catch(InterruptedException ex) { System.err.println(ex); } }//end of while }//end of run }//end of class moveDisk
強調部分が主要な変更です。
lx に x を記憶しておき、次の円を描くまえにそれを背景色で塗りつぶします。
やはり複数の●を動かせますし、green, blue も生きています。
左右で跳ね返ることを確認しなさい。