The example below illustrates the flickering problem. Moving the
image with the mouse causes both the background and the image to
flicker.
|
import
java.awt.*;
import java.awt.event.*;
import java.applet.*;
public
class FlickerMax_Applet7 extends Applet
implements MouseMotionListener
{
int numBands = 12;
int currentX, currentY;
Image image;
public void init()
{
String imageName = getParameter("ImageName");
if(imageName == null) imageName
= "Apollo16Lander.gif";
String numBandStr = getParameter("NumBands");
if( numBandStr != null)
numBands = Integer.parseInt(numBandStr);
img=getImage(getCodeBase(),"monaSmall.gif"
);
addMouseMotionListener(this);
}
//
Get the mouse dragging coordinates.
public void mouseDragged( MouseEvent e ) {
currentX = e.getX();
currentY = e.getY();
repaint();
}
// Override mouseMoved with
empty method.
public void mouseMoved ( MouseEvent e){}
public void paint( Graphics g ) {
int wd = getSize().width;
int ht = getSize().height;
int wBand = wd/numBands;
boolean changeBand = false;
// Draw stripped
background
int xStart = 0;
for ( int y = 0; y < ht; y++ )
{ changeBand = false;
for ( int x = xStart; x <
wd; )
{ g.setColor(
(changeBand
= !changeBand) ? Color.RED : Color.BLUE );
g.fillRect(
x, y, wBand, 1); x += wBand; }
xStart
-= 1; if( (-xStart) > wBand)
xStart
= 0;
}
// then the image
g.drawImage( image, currentX, currentY,
this );
}
}
|
After repaint()
is called, a request for drawing is put into a queue in the AWT
graphics engine. When the request is process, the paint()
method is not called directly. Instead, the update()
method is invoked. This method clears the component face by drawing
a rectangle the size of the component with the background color.
Since in this case, we redraw the whole applet anyway,
there is no need for update()
to waste time clearing it. So the following apple overrides update()
with a version that just calls paint():
Update_Applet7.java
Resources: Apollo16Lander.jpg
|
import
java.awt.*;
import java.awt.event.*;
java.applet.*;
public
class Update_Applet7 extends Applet
...
...
// Override update to
prevent clearing of
// background since the whole frame will be
// drawn over anyway.
public void update ( Graphics g )
{ paint(g); }
public void paint( Graphics g )
{
...
|
References & Web Resources
Latest update: March 8, 2006
|