关于Frame和JFrame的repaint()方法差别的疑问

nyzhl 2007-08-12 10:51:34
现象:在JFrame中update方法的文档说明是Just call paint()。每次repaint重绘时,背景不重绘。要重绘背景要么在paint里调用super.paint();要么自己在paint里写重绘背景代码。重写update方法不管用。
在Frame里都很正常,就像网上说的一样repaint调用update,update重绘背景后调用paint。但是在JFrame里怎么不对呢。难道JFrame的工作细节和Frame不一样?或者他就不调用update,在JFrame中,我把update重写成空函数,调用repaint时仍然按paint方法重绘
...全文
1048 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Simon_LY 2008-04-13
  • 打赏
  • 举报
回复
public void update(Graphics g){
paint();
}//swing中update的定义
因此,要清屏重绘,覆写paint(),调用父类的paint()即可,即super.paint();
nyzhl 2007-08-15
  • 打赏
  • 举报
回复
JFrame.repaint()不调用update而直接调用paint吗????
nyzhl 2007-08-13
  • 打赏
  • 举报
回复
repaint不是先调用update 在update里调用paint吗
在Frame里是这样
但是在JFrame里update似乎从来就没有被调用过呢?
我在update里面加上System.out.println("I am being invoked");
证实在Frame里不停地打印I am being invoked
在JFrame里没反应
jiayuewei 2007-08-13
  • 打赏
  • 举报
回复
Programs may trigger a future call to paint() by invoking repaint(), but shouldn't call paint() directly.
不会直接调用paint()
Programs may trigger a future call to paint() by invoking repaint(), but shouldn't call paint() directly.
nyzhl 2007-08-13
  • 打赏
  • 举报
回复
示例源码:
在窗口里画一个小圆球,然后向右下方移动
窗口类MyJFrame如果继承自Frame则一切正常,继承自JFrame则背景不刷新
在JFrame版本中update方法不起作用,要实现双缓冲只有在paint里写代码才行
怎么会这样呢 ? Frame和JFrame差别很大吗?


import java.awt.*;
import javax.swing.*;

public class JFrameTest {
public static void main(String[] args) {
new MyJFrame();
}
}
class MyJFrame extends JFrame {
private final int wid = 600;
private final int hei = 400;
private Point pos = null;
private Image buffer = null;
public MyJFrame() {
pos = new Point(0,0);
setSize(wid,hei);
setVisible(true);
new Thread(new Move()).start();
}
public void paint(Graphics g) {
Color temp = g.getColor();
g.setColor(Color.BLACK);
g.fillOval(pos.x,pos.y,50,50);
g.setColor(temp);
}
public void update(Graphics g) {
if (buffer == null) {
buffer = this.createImage(wid,hei);
}
Graphics bg = buffer.getGraphics();
bg.setColor(Color.PINK);
bg.fillRect(0,0,wid,hei);
paint(bg);
g.drawImage(buffer,0,0,null);
}
private class Move implements Runnable {
public void run() {
while(true) {
pos.x++;
pos.y++;
repaint();
try {
Thread.sleep(20);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
nyzhl 2007-08-13
  • 打赏
  • 举报
回复
自己顶

62,623

社区成员

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

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