Skip to main content

Cached Painter

No replies
irond13
Offline
Joined: 2007-06-26
Points: 0

Hi all,

here is a simple cached painter I've created which should eliminate alot of unneccessary painting calls:

</p>
<p>package com.square.swingx;</p>
<p>import java.awt.Graphics2D;<br />
import java.awt.image.BufferedImage;<br />
import org.jdesktop.swingx.graphics.GraphicsUtilities;<br />
import org.jdesktop.swingx.painter.Painter;</p>
<p>/**<br />
 *<br />
 * @author Pierre Jansen<br />
 */<br />
public class CachedPainter implements Painter {</p>
<p>    private Painter delegatePainter = null;</p>
<p>    private BufferedImage cache = null;</p>
<p>    private boolean invalid = false;</p>
<p>    public CachedPainter(Painter delegatePainter) {<br />
        if (delegatePainter == null)<br />
            throw new IllegalArgumentException("Delegate painter cannot be null");</p>
<p>        this.delegatePainter = delegatePainter;<br />
    }    </p>
<p>    public void paint(Graphics2D g, T object, int width, int height) {<br />
        checkCachedImage(width,height,object);<br />
        g.drawImage(cache, 0, 0, null);<br />
    }</p>
<p>    private void checkCachedImage(int width, int height, T object) {<br />
        if (invalid || cache == null || cache.getWidth() != width || cache.getHeight() != height) {<br />
            cache = GraphicsUtilities.createCompatibleTranslucentImage(width, height);<br />
            Graphics2D g2 = cache.createGraphics();<br />
            delegatePainter.paint(g2, object, width, height);<br />
            g2.dispose();<br />
            invalid = false;<br />
        }<br />
    }</p>
<p>    public void markAsInvalid() {<br />
        invalid = true;<br />
    }</p>
<p>}</p>
<p>

do with it as you please.

Regards,
Pierre