大哥,大姐救命啊!
我想用定时器定时的在窗体里面画出一个移动的小方格,但是出乎我的意料的是,出来了一长串的方格,我想知道这究竟是怎么回事,还希望大哥大姐们能给出个解决方案!
下面是我的代码import java.util.Timer;
import java.util.TimerTask;
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame{
private int x=100,y=100;
Test(){
super("ok");
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Timer time=new Timer();
time.schedule(new TimerTask() {

@Override
public void run() {
// TODO Auto-generated method stub
x+=10;y+=10;
repaint();
//update(getGraphics());
}
}, 1000,500);
}
public void paint(Graphics g){
g.setColor(Color.red);
g.fillRect(x, y, 10, 10);
}
public static void main(String[] args){
Test e=new Test();
}
}

解决方案 »

  1.   

    在paint函数里面加上super.paint(g);清除之前画的东西import java.util.Timer;
    import java.util.TimerTask;
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame{
    private int x=100,y=100;
    Test(){
    super("ok");
    setVisible(true);
    setSize(500,500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Timer time=new Timer();
    time.schedule(new TimerTask() {@Override
    public void run() {
    // TODO Auto-generated method stub
    x+=10;y+=10;
    repaint();
    //update(getGraphics());
    }
    }, 1000,500);
    }
    public void paint(Graphics g){
    super.paint(g); //加上这句话
    g.setColor(Color.red);
    g.fillRect(x, y, 10, 10);
    }
    public static void main(String[] args){
    Test e=new Test();
    }
    }