import java.awt.*; import java.awt.event.*; import java.applet.*; import java.util.*; public class digwatch extends Applet implements Runnable { Thread w_clock = null; Date w_date; /**アプレットの初期化*/ public void init() { //スレッドの起動 w_clock = new Thread(this); w_clock.start(); } public void paint(Graphics g) { g.setColor(Color.darkGray); g.fillRect(0,0,200,60); //背景を塗る g.setColor(Color.green);// 緑色でテキストの色を設定 w_date = new Date(); g.drawString(w_date.toString(), 10, 30); } public void run() { while (true) { // 再描画 repaint(); try { Thread.sleep(1000); } catch(Exception e) {} } } }
<HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=Shift_JIS"> <TITLE> HTML テストページ </TITLE> </HEAD> <BODY> ディジタルカレンダ時計です。<BR> <APPLET CODEBASE = "." CODE = "digwatch.class" NAME = "TestApplet" WIDTH =230 HEIGHT = 60 > </APPLET> </BODY> </HTML>
nowx += gox; nowy += goy;ただし、ボールが表示枠の右、左に達したら、gox の符号を変えて、移動方向を逆にします。これが「跳ね返り」になります。
if(nowx > this.getWidth() - 8 || nowx < 0) gox = -gox;ここで、this.getWidth() は枠(アプレットウインドウ)を示します。上下方向にも同様な処理が必要です。
import java.applet.*; import java.awt.*; /* <applet code="ballmove" width="100" height="100"></applet> */ public class ballmove extends Applet implements Runnable{ int gox = 2;//動く距離 int goy = 2; int nowx,nowy;//現在地 Thread move; boolean go = false; public void init(){ nowx = this.getWidth()/2;//中心から開始 nowy = this.getHeight()/2; //色の設定 // setBackground(Color.white);//背景 setBackground(Color.yellow);//背景 // setForeground(Color.blue);//前景 setForeground(Color.orange);//前景 go = true; move = new Thread(this);//スレッド生成 move.start(); }//init /* public void start(){ go = true; move = new Thread(this);//スレッド生成 move.start(); }//start */ public void run(){ while(go){ //端まできたら折り返す if(nowx > this.getWidth() - 8 || nowx < 0) gox = -gox; if(nowy > this.getHeight() - 8 || nowy < 0) goy = -goy; //現在の座標に移動分を加える nowx += gox; nowy += goy; repaint();//再描画 try{ Thread.sleep(250); } catch(Exception e){ go = false; } }//while }//run public void paint(Graphics g){ g.fillOval(nowx,nowy,8,8);//円を描く }//paint }
スレッドでボールを動かします。