Search code examples
javaswingdrag-and-dropgraphics2d

Flickering while dragging in Swing


I have such code:

public class DpDropTargetListener implements DropTargetListener {
   public void dragOver(final DropTargetDragEvent dtde) {
      ...
      if (dtde.getLocation().equals(container.getLastLocation())) {
         return;
      }
      ...     
      Rectangle visRect = container.getVisibleRect();
      container.paintImmediately(visRect.x, visRect.y, visRect.width, visRect.height);

      //prepare the image to paint, and paint it
      ...
      Graphics2D gr = (Graphics2D) container.getGraphics();            
      gr.drawImage(container.getDragImage(), AffineTransform.getTranslateInstance(
         x, y), null);
      ...
   }
}

It should draw specified image while dragging. But this image is flickering when I drag it. What should I correct to stop flickering?


Solution

  • Override the container's paintComponent() method. During drag set the image and location in the container and call normal repaint();