Problem serializing chart - solved!

A discussion forum for JFreeChart (a 2D chart library for the Java platform).

Problem serializing chart - solved!

Postby cgmollo » Thu Nov 17, 2016 3:41 pm

I was getting a serialization exception when I tried to serialize a JFreeChart chart to a file. I eventually figured out the problem, so I am posting the solution here so that maybe this post will help someone else someday. :)

The error message (NotSerializableException) and corresponding stack trace offered little in the way of clues. I finally figured out that the problem was with an interface implementation I had set for generating custom legend item labels. I used a lambda expression to supply the interface (XYSeriesLabelGenerator) implementation. Alternatively, one might use an anonymous inner class to provide the implementation. Neither of these approaches will work, as it is not possible (as far as I know) to implement the Serializable interface for the implementation. So, I used the good, old, named top-level class:

Code: Select all
public class CustomSeriesLabelGenerator implements XYSeriesLabelGenerator,
                                                   Serializable {
    public String generateLabel(XYDataset dataset, int seriesIndex) {
        String label;
        try {
            XYSeriesCollection collection = (XYSeriesCollection) dataset;
            label = collection.getSeries(seriesIndex).getDescription();
        } catch (ClassCastException cce) {
            label = "Series" + seriesIndex;
        return label;

And then:

Code: Select all
XYItemRenderer renderer = ...;
renderer.setLegendItemLabelGenerator(new CustomSeriesLabelGenerator());

They key thing is that my implementation of XYSeriesLabelGenerator could now also implement the Serializable interface.
Posts: 2
Joined: Tue Sep 22, 2015 2:43 pm

Return to JFreeChart

Who is online

Users browsing this forum: Google [Bot] and 4 guests