Martin Carney Martin Carney - 1 year ago 88
Java Question

Customize color for individual Domain axis tick labels

I have a JFreeChart which I'm running through a customizer (JRAbstractChartCustomizer). I have figured out how to color individual bars and item labels according to the data (eg green for >90%, yellow for 75-90%, red for <75%) by extending BarRenderer and overriding

getItemLabelPaint(int row, int column)
getItemPaint(int row, int column)
. Each bar has a corresponding tick with a String label, since the domain is by name rather than by numeric value. I need a way to individually color the tick labels based on the value similar to how I color the bars and the item labels.

What method do I override in BarRenderer, or what other thing do I do in my JRChartCustomizer to override the color on an individual basis.

What I'm doing for the item labels: (I want to do basically the same thing, but for tick labels)

class CustomBarRenderer extends BarRenderer {

private final Color COLOR_GREEN = new Color(0, 227, 0);
private final Color COLOR_YELLOW = new Color(247, 210, 0);
private final Color COLOR_RED = new Color(237, 26, 0);

public Paint getItemLabelPaint(int row, int col) {
CategoryDataset cDataset = getPlot().getDataset();

if (cDataset != null) {
Number itemValue = cDataset.getValue(row, col);

String rowKey = cDataset.getRowKey(row).toString();
String colKey = cDataset.getColumnKey(col).toString();

if (itemValue != null) {
int intVal = itemValue.intValue();

if (intVal > yellowHigh) {
} else if (intVal >= yellowLow) {
} else {
return COLOR_RED;

// if all else fails...
return super.getItemLabelPaint(row, col);

public Paint getItemPaint(int row, int col) {
... similar to above ...

Answer Source

Your chart's domain axis tick label is rendered by a CategoryAxis. You can use setTickLabelPaint() to color labels by category. The example below modifies BarChartDemo1 to make the "Test" category label a shade of green.


CategoryPlot plot = (CategoryPlot) chart.getPlot();
CategoryAxis domain = plot.getDomainAxis();

For finer control, you can override getTickLabelPaint() in a custom CategoryAxis that has access to the dataset referenced by your CustomBarRenderer. The existing implementation uses a Map<Category, Paint> as a lookup table. The Map is private, but the approach may give you an idea of how to proceed.