2011-01-07 24 views
0
//I want to paint a ball in a animation 
//I can't seem to find a way to repaint the ball 
// Any help or tips on how to use repaint here? 
// 

     // Ball class 
    import javax.swing.*; 
     import java.awt.*; 
     import java.awt.event.*; 
     import java.util.*; 
     public class Ball implements Runnable { 
     protected Point loc; 
     protected int dx; 
     protected int dy; 
     protected Color color; 
     protected boolean flag; 
     private Graphics gra; 
     public Ball(Point loc,int dx,int dy,Graphics st) 
     { 
      this.loc=loc; 
      this.dx=1; 
      this.dy=1; 
      color=Color.blue; 
      this.gra=st; 
      flag=false; 
     } 
     public void paint(Graphics g) 
     { 
      g.fillOval((int)this.loc.getX(),(int)this.loc.getY(),20,20); 
     } 
     public void move() 
     { 
      this.loc.translate(this.dx,this.dy); 
     } 

     @Override 
     public void run() { 
      while(flag==false) 
      { 
       this.paint(gra); 
       try { 
        Thread.sleep(20); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       move(); 
      } 
     } 

     } 


//Myframe class 
import javax.swing.JFrame; 
import java.awt.*; 
import java.awt.event.*; 
public class myframe extends JFrame { 
    private Ball b; 
    public myframe() 
    { 
     super("My Frame"); 
     setSize(800,600); 
    } 
    public void run() 
    { 
     b=new Ball(new Point(100,100),10,10,getGraphics()); 
     b.run(); 
    } 
} 

//Main class 
import javax.swing.JFrame; 
import java.awt.*; 
import java.awt.event.*; 
public class Main extends JFrame 
{ 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     myframe jwin = new myframe(); 
     jwin.setSize(600, 600); 
     jwin.setVisible(true); 
     jwin.run(); 
    } 
} 

答えて

1

あなたが代わりにthis.paint(gra)repaint()を使用してみてください、そして、あなたもあなたにグラフィックインターフェース

をコンポーネントを追加する必要があるスレッドの中に置く必要があります
1

JComponentクラスのpaintComponent()メソッドをオーバーライドする必要があります。あなたのペイントを行い、GUIにそのコンポーネントを追加してください。

関連する問題