DEV Community

Dr Nilo Stolte
Dr Nilo Stolte

Posted on • Updated on

Java Graphics2D: you don't need double buffering

If you are into Java programming this might sound to you as a big surprise and almost as a huge heresy. No, you just don't need a JPanel and you definitely don't need double buffering.

What you need is just a JFrame and buffering with a BufferedImage, where you save your Graphics2D using createImage. You then use drawImage to display the saved buffer whenever you need to refresh the whole JFrame. Never redisplay your whole JFrame with Graphics2D primitives, but only with the BufferedImage. You can redisplay only parts of the JFrame. In this case your JFrame "paint" method must know what part to update by selective painting (like highlighting a button when clicked).

This is far much faster than double buffering and you will never see any flickering. Thus you will have the best performance with the same result as using a JPanel and double buffering.

But that is not the only advantage. It also allows easily zooming your entire window (by using setSize method) because you are dealing with the JFrame directly. Every time your window changes size (for example, by clicking on a magnifier lens with "+" or "-" icon) you create a new BufferedImage for the redisplay. This concept is a desirable feature when you are dealing with vector graphics interfaces (basically using Shape and Graphics2D), as zooming can become part of the interface.

It might sound weird to talk about vector graphics and a pixelized BufferedImage at the same time. However, a Shape is first scan-converted before being displayed. By using a buffer you are just anticipating and cutting down scan-conversion time. This is extremely useful in complex vector graphics interfaces. It is a know fact that what is deterring the generalized use of vector graphics in GUIs, either in embedded applications, either on the web, is that it is quite time consuming.

This will likely change in the near future when hyper high resolution screens will appear and programs will have to deal with a wide range of screen resolutions. Vector graphics will then be the most elegant solution to this problem. Using lots of photos and images in your web sites? If they are only for decoration you will probably be in trouble when this arrives.

Top comments (0)