package scf.luffy;import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;import javax.swing.JFrame;
import javax.swing.SwingUtilities;public class Bell extends JFrame { private int x1 = 100;
private int y1 = 100;
private int x2 = 100;
private int y2 = 100; private static final long serialVersionUID = -8672941220924959402L; Bell() {
setLayout(new GridLayout(1,1));
setSize(500, 500);
setLocation(100, 100);
setResizable(false);
setVisible(true);
Thread t = new GoGoGo();
SwingUtilities.updateComponentTreeUI(this); 
t.start(); } public void paint(Graphics g) {
/**/  
Graphics2D g2d = (Graphics2D) g;
setBackground(Color.PINK);
g2d.setColor(Color.red);  
g.drawRect(x1, y1, x2, y2);// 画矩形

 
} class GoGoGo extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
x1 += 10;
x2 += 10;
y1 += 10;
y2 += 10;
System.out.println(x1);
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

repaint();
validate();  
}
}
} public static void main(String[] args) {
new Bell();
}
}以上代码运行后 会画出许多 图形,但是实际上就是一个,没有刷新而已。怎么让他能刷新啊~

解决方案 »

  1.   

    在setBackground(Color.PINK);后
    加句 
    g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
    意思也很清楚了吧?
    记得结帖哦 :)
      

  2.   

    在下面这个方法里加一句代码就可以了.g.clearRect(0,   0,   500,   500); public   void   paint(Graphics   g)   { 
    /**/ g.clearRect(0,   0,   500,   500);  
    Graphics2D   g2d   =   (Graphics2D)   g; 
    setBackground(Color.PINK); 
    g2d.setColor(Color.red);   
    g.drawRect(x1,   y1,   x2,   y2);//   画矩形   
      

  3.   

    在setBackground(Color.PINK);后 
    加句   
    g2d.clearRect(0,   0,   this.getWidth(),   this.getHeight());----------------------
    正解了
      

  4.   

    两种方法:
    1,让你的类实现Runnable接口,重写它的run()方法,
        public void run() {
          while(true) {
            repaint();//不停的重画
            try {
              Thread.sleep(100) ;//每画一次让线程睡眠100ms,也可以是其他的时间,自定义
            }catch(Exception e) {
              e.printStackTrace() ;
             }
            }
          }
        }2,另外写一个内部类,实现Runnable接口,重写它的run()方法,重写的方法是一样的当然你要在某个时候把线程启动,启动的方法是
    对于后者:Thread t = new Thread(new repaintThread()) ;//repaintThread() 是那个内部类
    t.start() ;
    对于前者:在main方法里这样处理
    Bell b = new Bell() ;
    b.start() ;