import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 

public class Rei52 extends JFrame implements Runnable, ActionListener{

       private int x=100, y=0;

       private volatile Thread th=null;        // スレッドオブジェクトのための変数th(初期値はnull

      

       class Rei52Panel extends JPanel{

              public void paintComponent(Graphics g){   // swingパッケージではpaintComponentを使う

                     super.paintComponent(g);

                     Font f=new Font((g.getFont()).getName(), Font.BOLD,40);

                     g.setFont(f);

                     g.drawString("",x,y);

              }

       }

      

       // コンストラクタ

       public Rei52(){

              setSize(300,250);

              addWindowListener(

                     new WindowAdapter(){

                            public void windowClosing(WindowEvent e){

                                   System.exit(0);

                            }

                     }

              );

              Container c=getContentPane();

              c.add(new Rei52Panel(), "Center");

              JButton bt1 = new JButton("開始/停止");

              c.add(bt1,"North");

              bt1.addActionListener(this);

       }

      

       public void actionPerformed(ActionEvent e){

              if(th==null){           // thnullということは現在スレッドthが動作していない

                     th=new Thread(this);              // 新しい別のスレッドを作る

                     th.start();                            // 別スレッドを実行する(runメソッドが別のスレッドで動作を始める)

              }

              else                      // thnullでなかったということは、現在スレッドthが動作している

                     th=null;               // thnullにするとrunメソッド中のループが終了し、スレッドが終了する

       }

      

       public void run(){           // runメソッドはth.start()により別のスレッドとして起動する

              Thread thisThread = Thread.currentThread();

              while(th==thisThread){      

                     repaint();              // 再描画のためにpaintComponentを呼び出す

                     try{

                            th.sleep(300); // スレッドを300ミリ秒間一時停止する。こうすることで、ループは0.3秒に

//  1回実行される事になる

                     }

                     catch(InterruptedException e){}

                     x=x-10 ; y=y+10;

                     if(x<0){

                            x=(int) (Math.random()*getWidth() );

                            y=0;

                     }

              }

       }

      

       public static void main(String[] args){

              JFrame w=new Rei52();

              w.show();

       }

      

}