카테고리 없음

공 튀는거

bo97037 2014. 12. 9. 07:12

package ex_01;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;

import javax.swing.JFrame;
import javax.swing.JPanel;

class Ball{
 private int x,y,sx,sy,w,h;
 
 Ball(int width,int height){
  w=width;h=height;
  x=(int)(Math.random()*w);
  y=(int)(Math.random()*h);
  sx=(int)(Math.random()*5+1);
  sy=(int)(Math.random()*5+1);
 }

 public void run(Graphics g) {
 x=x+sx;y=y+sy;
 if(x>=w || x<=0 ) sx = -sx;
 if(y>=h || y<=0 ) sy = -sy;
 g.fillOval(x,y,10,10);
 }
}


public class RectTest extends JFrame{
 public RectTest(){
  
 }
 
 public static void main(String[] args)
 {
     int width = 500,height=400;
     int n = 20;
     Ball[] b = new Ball[n];
     for(int i = 0; i < n;i++)
      b[i]=new Ball(width,height);
     JFrame f = new JFrame();
     f.setSize(width, height);
     f.setDefaultCloseOperation(3);
     f.setVisible(true);
    
     JPanel p = new JPanel(){
      public void paint(Graphics g){
       super.paint(g);
       for(int i= 0; i < n;i++)
        b[i].run(g);
      }
     };
     f.add(p);
    
     new Thread(new Runnable(){
      public void run(){
       while(true){
        try {
      Thread.sleep(20);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }p.repaint();
       }
      }
     }).start();
 }
}