Search code examples
javajfreechart

Apply image/pattern to pie section instead of normal color


Instead of using normal plot.setSectionPaint() method to fill color of the pie section, is it possible to add a pattern or a image as shown below.

I have got this requirement as the colors are difficult to distinguish when printed in black & white printer.

Worst case if not possible then I will have to use 2 very different colors which are easily distinguishable over b/w printer

pie chart


Solution

  • setSectionPaint allows any implementation of the interface java.awt.Paint to be passed. Color is one class that implements Paint, but there are others, such as TexturePaint.

    This code will create a TexturePaint like the blue line pattern in your example:

    BufferedImage texture = new BufferedImage(1, 30, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = texture.createGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, 1, 30);
    g.setColor(new Color(0x26A2D6));
    g.fillRect(0, 0, 1, 20);
    g.dispose();
    
    TexturePaint texturePaint = new TexturePaint(texture,
        texture.getRaster().getBounds());
    

    You can then pass that texturePaint as the argument to setSectionPaint.