Previous Table of Contents Next

Painter Tutorial

A new API has been introduced in the SwingX project called Painter. A Painter is a delegate that JXPanel and other SwingX components can delegate to for painting their backgrounds.

Note: Download a daily build after March 22, 2006 to get access to the Painter API

In the past, if I wanted to use a GradientPaint to paint the background of a JPanel I would have to subclass JPanel and override the paintComponent method to use the gradient. There are several drawbacks to this approach. First, I cannot use gradients with components that cannot be replaced. For example, if I use a third party component such as a LoginDialog, I may not be able to get access to replace the underlying JPanels. Second, I cannot change the background display of a JPanel at runtime -- I would have to swap out the JPanel component dynamically!

These and other considerations led to a very modest Painter API. Let me state clearly that this Painter API does not pretend to be a general solution, rather one that is available today. In Swing we will want to use a more general solution that allows you to insert a painter either for the Component background, foreground, in between, beneath the background, above the foreground, etc. It isn't reasonable to implement such a thing at this time in SwingX, so I've opted for the less intense, yet very capable, Painter API currently in SwingLabs.

As an example of what you can do with Painters, below is a screenshot and the code that was used to generate the screenshot. Note that there isn't any Java2D code here, no subclassing, no images.

    Color blue = new Color(0x417DDD);
    Color translucent = new Color(blue.getRed(), 
                                  blue.getGreen(),
                                  blue.getBlue(), 100);

    Painter background = new MattePainter(blue);
    PinstripePainter pinstripes = new PinstripePainter(45);
    pinstripes.setPaint(Color.WHITE);
    BasicGradientPainter veil = new BasicGradientPainter(new GradientPaint(
            new Point2D.Double(.4, 0),
            blue,
            new Point2D.Double(1, .5),
            translucent));

    CompoundPainter p = new CompoundPainter(background, pinstripes, veil);
    p.setAntialiasing(RenderingHints.VALUE_ANTIALIAS_ON);
    jxpanel.setBackgroundPainter(p);
                    

Another example contains one single image: the shield in the top left. Otherwise, again, its all done with painters:

private void setupPainters() {
    GlossPainter gloss = new GlossPainter(new Color(1.0f, 1.0f, 1.0f, 0.2f),
        GlossPainter.GlossPosition.TOP);

    PinstripePainter stripes = new PinstripePainter();
    stripes.setPaint(new Color(1.0f, 1.0f, 1.0f, 0.17f));
    stripes.setSpacing(5.0);

    MattePainter matte = new MattePainter(new Color(51, 51, 51));

    header.setBackgroundPainter(new CompoundPainter(matte, stripes, gloss));
}
                    



Previous Table of Contents Next