现象:在JFrame中update方法的文档说明是Just call paint()。每次repaint重绘时,背景不重绘。要重绘背景要么在paint里调用super.paint();要么自己在paint里写重绘背景代码。重写update方法不管用。
在Frame里都很正常,就像网上说的一样repaint调用update,update重绘背景后调用paint。但是在JFrame里怎么不对呢。难道JFrame的工作细节和Frame不一样?或者他就不调用update,在JFrame中,我把update重写成空函数,调用repaint时仍然按paint方法重绘

解决方案 »

  1.   

    示例源码:
    在窗口里画一个小圆球,然后向右下方移动
    窗口类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();
    }
    }
    }
    }
    }
      

  2.   

    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.
      

  3.   

    repaint不是先调用update  在update里调用paint吗
    在Frame里是这样
    但是在JFrame里update似乎从来就没有被调用过呢?
    我在update里面加上System.out.println("I am being invoked");
    证实在Frame里不停地打印I am being invoked
    在JFrame里没反应
      

  4.   

    JFrame.repaint()不调用update而直接调用paint吗????
      

  5.   

    public void update(Graphics g){
     paint();
    }//swing中update的定义
    因此,要清屏重绘,覆写paint(),调用父类的paint()即可,即super.paint();