Skip to main content

Drag and Drop Effects and Java2D Performances

Posted by gfx on October 3, 2005 at 9:09 PM PDT

You can run the WebStart demo or download its source code.

Once the application is started, you can drag and drop pictures from the list on the left to the image viewer on the right and trigger a cool looking animation.

Photo Collage
Photo Collage

When writing this application, I found serious performances issues with J2SE 1.5. There were also some problems with Java SE 1.6 but far less important. Chris Campbell and Chet Haase really helped me on this. It turns out that loading an image with ImageIO does not necessarily provide a picture in a compatible format with the default screen configuration. When drawing such pictures you lose performances, especially when scaling them. An easy way to work around this problem is to convert them into compatible images:

  public static BufferedImage loadCompatibleImage(URL resource) throws IOException {
    BufferedImage image = ImageIO.read(resource);
    GraphicsConfiguration configuration = GraphicsEnvironment.
      getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    BufferedImage compatibleImage = configuration.createCompatibleImage(image.getWidth(),
                                                                        image.getHeight());
    Graphics g = compatibleImage.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return compatibleImage;
  }

I wrote a longer explanation you might want to check out if you need to perform heavy drawings with pictures in your application.