1

I am new to JFreeChart and I am trying to see what action do what.

In my chart I only have one series, and I would like -according to the value- to set a different color for the bar. For example : 0-20 -> RED, 20-80 -> YELLOW, 80-100 -> GREEN

CategoryPlot plot = chart.getCategoryPlot();
CategoryDataset dataset = plot.getDataset(0);

Number value = dataset.getValue(dataset.getRowKey(0), dataset.getColumnKey(0));
Double val = value.doubleValue();

if (val <= 20.0) {
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    Paint tmp = renderer.getItemPaint(row, column);

    /*
    ** Help Please
    */      
}

return chart;

This is where I reached, I am stuck here and don't know really where to go. I saw in the documentation that Paint is an interface but none of the class implementing this interface does provide a setXXX() method. So, my two questions are :

  • How do I set a color to a single Bar ?
  • How do I apply that to my chart ?
Nazaf Anwar
  • 339
  • 1
  • 8
  • 17
Spredzy
  • 4,982
  • 13
  • 53
  • 69

1 Answers1

3

You'll need to create your own subclass of BarRenderer and override getItemPaint(). Instead of choosing a color based on column, choose it based on your value. Here's an outline to show how the existing BarRenderer works.

plot.setRenderer(new MyRender());
...
class MyRender extends BarRenderer {

    @Override
    public Paint getItemPaint(int row, int col) {
        System.out.println(row + " " + col + " " + super.getItemPaint(row, col));
        return super.getItemPaint(row, col);
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Thank you for the answer. I have a question, getItemPaint is supposed to return me a Paint class, but if I want to set a color for a define (row, col) attributes does is still take place in the getItemPaint? – Spredzy Mar 31 '11 at 11:28
  • AFAIK, yes; the API recommends overriding `getItemPaint()` "if you require different behavior." Click on the `getItemPaint()` or `lookupSeriesPaint()` link to see the default implementation. – trashgod Mar 31 '11 at 11:46