• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 441
  • Last Modified:

dragging & resize image on canvas with out flickering

whenever i  drag the image on the
canvas the image is getting flickered so i want to reduce the flickering of image and also flush the old image on the canvas.i tried out with double
buffering concept,but i coudn't get it.
so please give the suggestion.
1 Solution
Ok, here's a small applet that allows dragging an image around, it uses double buffering and doesn't flicker.

import java.awt.*;
import java.applet.*;

public class MyApplet extends Applet{

  public void init(){
    MyComponent comp = new MyComponent(getCodeBase(),"image.gif");


class MyComponent extends Canvas{

  private Image dbImage; // Image for double buffering, to avoid flickering.
  private Image myImage;
  private int imageX=0, imageY=0; // The location of our image;

  private int lastDragX, lastDragY;

  public MyComponent(Image image){
    myImage = image;

  public void update(Graphics g){
     Graphics dbGraphics = getDBGraphics();

  public void paint(Graphics g){

   public boolean mouseDown(Event e, int x, int y){
      lastDragX = x;
      lastDragY = y;
      return false;

  public boolean mouseDrag(Event e, int x, int y){
     imageX += x-lastDragX;
     imageY += y-lastDragY;
     lastDragX = x;
     lastDragY = y;
     return false;


  private final Graphics getDBGraphics(){
 if ((dbImage == null) || ((dbImage.getWidth(null)!=bounds().width)||
   dbImage = createImage((int)Math.max(bounds().width,1),
        // Using Math.max is needed because createImage only takes positive
        // values, which seems strange to me, since components can even
        // have negative size.
    return dbImage.getGraphics();


I'm really surprised to find this question unanswered.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now