I have an ArrayList
that gets data from user input, and I have created a button which when activated launches an XY Line graph. The problem I have is I keep getting errors and my LineGraph
wont create.
I don't really know how to get the data from my ArrayList
and put it in an XYSeries
.
Iterator it = dataXY.iterator();
XYSeries p1 = new XYSeries("XY");
while( it.hasNext()) {
p1.add((XYDataItem) it.next());
}
XYSeriesCollection xydata = new XYSeriesCollection();
xydata.addSeries(p1);
JFreeChart lineChart = ChartFactory.createXYLineChart("XY chart", "X", "Y", xydata, PlotOrientation.HORIZONTAL, true, true, false);
lineChart.setBackgroundPaint(Color.WHITE);
final XYPlot plot = lineChart.getXYPlot();
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setSeriesPaint(0, Color.BLACK);
renderer.setSeriesStroke( 0 , new BasicStroke( 4.0f ) );
plot.setRenderer( renderer );
plot.setBackgroundPaint(Color.WHITE);
ChartFrame frame = new ChartFrame ("XY Line Graph", lineChart);
frame.setVisible(true);
frame.setSize(700,500);
All this code is in the action event of my "create a graph" button. Any help on how to make this chart is greatly appreciated.
In the end I didnt even need to convert to an array although i managed to do that this way:
// converting arraylist to array
double [][] p1 = new double[dataXY.size()][dataXY.size()];
for (int i=0; i<dataXY.size(); i++) {
int x = dataXY.get(i).getX(); int y = dataXY.get(i).getY();
p1[i][0] = x;
p1[i][1] = y;
}
Anyway what i did was usean XYSeries and used a for loop to add all my values into the series like so:
XYSeriesCollection ds = new XYSeriesCollection();
XYSeries s1 = new XYSeries("XY data");
for (int i=0; i<dataXY.size(); i++) {
int x = dataXY.get(i).getX(); int y = dataXY.get(i).getY();
s1.add(y, x);
}
ds.addSeries(s1);