When trying to use double buffering, method createImage(int,int) returns null image object if used from within constructor. Why?

Kevin Riff

In order to do its thing, createImage(int, int) relies on the component's peer. However, the peer is not created until the component is made displayable for the first time. During your component's constructor, the peer is not available and so createImage(int, int) fails gracefully by returning null.

The best place to put the createImage(int, int) call is probably in the addNotify() method, after a call to super.addNotify(). Once super.addNotify() returns, the peer is guaranteed to be set and createImage(int, int) will work correctly.

public void addNotify() {
    buffer = createImage(width, height);