Thursday, September 29, 2016

Multiple XY-Line in a single Chart in Jasper Reports using JRBeanCollectionDataSource

Today, I had to create a xy-line chart with multiple lines in it. I know, with XY-Linechart with just single line it is pretty much easy to plot it and most of the blog would should that.But, None showed how to plot XY-chart with multiple lines and that too using JRBeanCollectionDataSource.It took me a lot of time to figure out for plotting it.That's the reason I am writing this blog.

Basic XY-Linechart is pretty much easy, where you just pass the datasource and it will be done. But, with just a small trick we can plot multiple xy-lines as well.
I am using JasperStudio 6.3.0

Jasper reports Part.


+> Create a Report

+> Remove all the unwanted Band from the report (except Summary) .

+> Create a Dataset or if you want to use main dataset then also it will work..I will be using main        Dataset.

+> Create a Parameter  'XYChartDataSource'  of type 'net.sf.jasperreports.engine.data.JRBeanCollectionDataSource'.



Create 3 fields as following




+> Now, Drag and drop a chart in SUMMARY  or TITLE band.(when you put chart in any other band, it will print chart multiple times).

+>  Select XY-Line Chart

+>  Set Following parameters









Java Part


Bean:
public class Coordinates {

    private Number series;
    private Number xCoordinate;
    private Number yCoordinate;

// Getters and Setters
}




Main class:

 List<Coordinates> coordinates1 = new ArrayList<>();
 List<Coordinates> coordinates2 = new ArrayList<>();
 List<Coordinates> coordinates3 = new ArrayList<>(); 

Map<String, Object> parameters = new HashMap<String, Object>(); 
//Getters & setters

coordinates1.add(new Coordinates("series 1", x-data ,y-data)); 
coordinates1.add(new Coordinates("series 1", x-data ,y-data)); 
coordinates1.add(new Coordinates("series 1", x-data ,y-data));  
...

coordinates2.add(new Coordinates("series 2", x-data ,y-data));
coordinates2.add(new Coordinates("series 2", x-data ,y-data));
coordinates2.add(new Coordinates("series 2", x-data ,y-data)); 
 ...

coordinates3.add(new Coordinates("series 3", x-data ,y-data)); 
coordinates3.add(new Coordinates("series 3", x-data ,y-data));
coordinates3.add(new Coordinates("series 3", x-data ,y-data));
..

// create separate bean object for each data-series
 JRBeanCollectionDataSource bean1 = new JRBeanCollectionDataSource(coordinates1);
 JRBeanCollectionDataSource bean2 = new JRBeanCollectionDataSource(coordinates2);
 JRBeanCollectionDataSource bean3 = new JRBeanCollectionDataSource(coordinates3);


// All Series Datasource Name should be same for all beans
parameters.put("XYChartDataSource", bean1);
parameters.put("XYChartDataSource", bean2);
parameters.put("XYChartDataSource", bean3);  


// same normal procedure for printing reports


No comments:

Post a Comment