Ensuring that previous graphical objects do not get erased with every repaint I'm trying to create a MS-Paint Style whiteboard for collaborative work across the net.

Robert Höglund Wanlert

Every time the repaint() method is called it , before the paint() method is called, calls the update() method which look like this:


public void update(Graphics g) {
  if ((this instanceof java.awt.Canvas) ||
     (this instanceof java.awt.Panel)  ||
     (this instanceof java.awt.Frame)  ||
     (this instanceof java.awt.Dialog) ||
     (this instanceof java.awt.Window)) {
    g.clearRect(0, 0, width, height);

  }
  paint(g);
} 

You can clearly see that the update() method will clear/erase the whole renderable area before the paint() (which in turn does all the painting) method is called. This brings up several problems...

First of all the update() method can cause a component to flicker because it clears the renderable area with each call to the repaint() method.

Second of all the update() method will clear all the prior painting. Therefore all your previous drawings will disappear.

I read that you cleared the renderable area with every paint() call.

In that case the area will be cleared two times. This will probably cause the flicker. I recommend that you override the update() method and implement it like this:


public void update(Graphics g) { paint(g); }

Some further workarounds may also be required...

[FAQ Manager Note] Be careful with this! Things may seem fine for a while with this, but there are two subtle problems:

  1. If you ever want something "removed" from the screen, you have to be sure to paint over it to make it disappear.
  2. If another window is dragged over yours, it creates a "damaged" area. You need to make sure you paint all of your component to handle damaged areas or things may seem to disappear.

Generally speaking, overriding update() like this is only a good idea if you're always repainting everything in the component, as in many animations. In cases like this, the erasing that update does causes flicker which is undesireable.

Remember to try whatever you come up with by dragging other windows on top of it, then moving them away!

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.