主题:求助,关于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();
}
}
}
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();
}
}
}