swing 刷新问题

luffyday 2007-11-21 11:40:10
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();
}
}

以上代码运行后 会画出许多 图形,但是实际上就是一个,没有刷新而已。

怎么让他能刷新啊~

...全文
130 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhb_821012 2007-11-21
  • 打赏
  • 举报
回复
在setBackground(Color.PINK);后
加句
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());

----------------------
正解了
luffyday 2007-11-21
  • 打赏
  • 举报
回复
汗~除了这个方法呢~~~~
dracularking 2007-11-21
  • 打赏
  • 举报
回复
嗯顶楼上 过程就是画了擦再重画 就是少了擦的过程
cursor_wang 2007-11-21
  • 打赏
  • 举报
回复
在下面这个方法里加一句代码就可以了.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);// 画矩形


}
shadao 2007-11-21
  • 打赏
  • 举报
回复
在setBackground(Color.PINK);后
加句
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());


意思也很清楚了吧?
记得结帖哦 :)
tuoxie007 2007-11-21
  • 打赏
  • 举报
回复
两种方法:
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() ;
约翰羊 2007-11-21
  • 打赏
  • 举报
回复
点左上角的"管理贴子"
luffyday 2007-11-21
  • 打赏
  • 举报
回复
顺便问一下 怎么结贴~

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧