我要做的是让一个方块,一直朝着某个方向运动,但是我运用repaint时,他并没有把上几个运动过的方块给擦除掉,还留着,不知道我哪个地方写错了,请大家帮帮忙看看,谢谢了.import javax.swing.*;
import java.awt.*;public class TankWar extends JFrame
{
    Tank t=new Tank();
    public void showFrame()
    {
        this.setTitle("坦克大战");
        this.setLocation(100,100);
        this.setSize(800,600);
        this.setBackground(Color.green);
        this.setResizable(false);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);
        new Thread(new RepaintThread()).start();
    }
    public void paint(Graphics g)
    {
        try
        {
            t.drawTank(g);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }    
    }
    //用于实现重画线程
    private class RepaintThread implements Runnable
    {
        public void run()
        {
          while(true)
            {
                 repaint();//这个地方的重画不知道为什么没有把从前绘过的图给擦掉
          //    System.out.println("=====");
                try
                {
                    Thread.sleep(1000);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[]args)
    {
        TankWar tk=new TankWar();
        Container c=tk.getContentPane(); 
    c.setBackground(Color.green);
        tk.showFrame();
        
    }
}class Tank 
{
    private final int WIDTH=30,HEIGHT=20;
    int intX,intY;
    int x,y;
    Tank()
    {
    }
    Tank(int x,int y)
    {
        intX=x;
        intY=y;
    }
    public void drawTank(Graphics g)
    {
        try
        {
            Color c=g.getColor();
            g.setColor(Color.RED);
            g.fillRect(x+40,y+40,WIDTH,HEIGHT);    
          g.setColor(c);
          x+=50;
          y+=5;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
    }
}

解决方案 »

  1.   

    JAVA交流与学习群:45609427  
    挑战技术,超越自我!!
      

  2.   

    drawTank句前清屏
    g.clearRect(0, 0, this.getWidth(), this.getHeight());
      

  3.   

    把原来的变量都赋值为0,因为你repaint()是重画,不会把原来画的都擦掉。
      

  4.   

    再问一下,如果把窗口缩小之后再放大
    会调用哪些方法,为什么这方法可以把从前的图形给擦了
    我自己调用的repaint方法却不行了
      

  5.   

    我明白了另一种解决的方法就是这样:
    public void paint(Graphics g) 
        { 
            try 
            { 
                super.paint(g); //对父类的组件也进行重新的绘制
                t.drawTank(g); 
            } 
            catch(Exception e) 
            { 
                e.printStackTrace(); 
            }     
        }