flicker = true;
repaint();
}
});
}
public void paint(Graphics g) {
Graphics screengc = null;
if (!flicker) {
screengc = g;
g = buffer.getGraphics();
}
g.setColor(Color.blue);
g.fillRect(0, 0, w, h);
g.setColor(Color.red);
for (int i=0; i<w; i+=gap)
g.drawLine(i, 0, w-i, h);
for (int i=0; i<h; i+=gap)
g.drawLine(0, i, w, h-i);
g.setColor(Color.black);
g.drawString("Press mouse button to double buffer", 10, h/2);
g.setColor(Color.yellow);
g.fillOval(mx - gap, my - gap, gap*2+1, gap*2+1);
if (!flicker) {
screengc.drawImage(buffer, 0, 0, null);
}
}
public void update(Graphics g) {
paint(g);
}
}
This simple applet has a complicated paint( ) method. It fills the background with blue
and then draws a red moiré pattern on top of that. It paints some black text on top of that and
then paints a yellow circle centered at the coordinates mx,my. The mouseMoved( ) and
mouseDragged( ) methods are overridden to track the mouse position. These methods are
identical, except for the setting of the flicker Boolean variable. mouseMoved( ) sets flicker
to true, and mouseDragged( ) sets it to false. This has the effect of calling repaint( ) with
flicker set to true when the mouse is moved (but no button is pressed) and set to false when
the mouse is dragged with any button pressed.
When paint( ) gets called with flicker set to true, we see each drawing operation as it
is executed on the screen. In the case where a mouse button is pressed and paint( ) is called
with flicker set to false, we see quite a different picture. The paint( ) method swaps the
Graphics reference g with the graphics context that refers to the offscreen canvas, buffer,
which we created in init( ). Then all of the drawing operations are invisible. At the end of
paint( ), we simply call drawImage( ) to show the results of these drawing methods all at once.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home