This has perhaps been asked before, but I haven't been able to find the answer through the search function. My question is, how might I retrieve the colour of a dataset on the chart? I'm using JFreeChart in a servlet and have form controls which allow you to add or remove a dataset. For usability, I would like to have the colours of the "remove dataset" list correspond with the colour of the bars on the chart.
Thanks in advance for any solutions.
Retrieving the colour of a dataset on a chart
-
- JFreeChart Project Leader
- Posts: 11734
- Joined: Fri Mar 14, 2003 10:29 am
- antibot: No, of course not.
- Contact:
Each colour is generally asssociated with a series in a chart. One dataset can contain multiple series, so it doesn't really make sense to talk about "the colour of a dataset", except in the special case where each dataset contains a single series.
To find the colour associated with a series, you need to look at the renderer used for the dataset that the series belongs to.
To find the colour associated with a series, you need to look at the renderer used for the dataset that the series belongs to.
David Gilbert
JFreeChart Project Leader
Read my blog
Support JFree via the Github sponsorship program
JFreeChart Project Leader


I apologize for the awkward wording, I was indeed referring to the colour of the series. I looked again at the XYLineAndShapeRenderer and XYBarRenderer classes (these are the renderers I'm using) and could only find methods which return a Paint object. This sounds promising, but I'm unsure how I can use this to find the actual colour of the series. I would like to retrieve the RGB values in 0-255 integers, or something similar which can be converted to a hex code to put on a cascading style sheet. Any thoughts?
I've found a solution to my problem. When I get the Paint object that is used to colour the bars in the XYBarRenderer, I cast it to a Color object on which I can then run functions like getRGB(), getRed(), etc. From looking at the javadoc for java.awt.Paint it wasn't obvious to me that this could be done, but it does work.
Perhaps this is obvious for people who have dealt with Java's Paint and Color classes before, but I'm certain I won't be the only person confused by them (or at least, one can hope).
Code: Select all
XYBarRenderer renderer = new XYBarRenderer();
Paint paint = renderer.getSeriesFillPaint(0);
Color color = (Color)paint;
System.out.println(color.getRGB());