回 帖 发 新 帖 刷新版面

主题:求助,关于repaint问题

我要做的是让一个方块,一直朝着某个方向运动,但是我运用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();
        }
        
    }
}

回复列表 (共2个回复)

沙发

public void paint(Graphics g)
    {
        try
        {
            super.paint(g);  //先调用父类的绘制组件的方法
            t.drawTank(g);
            Thread.sleep(100);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }    
    }

板凳


谢谢回答,明白了,又学会一点了,呵呵

我来回复

您尚未登录,请登录后再回复。点此登录或注册