Reputation: 3
I am learning java and I am trying to build an app. I'm stuck with this one last part of the application and was hoping some of you may be able to help me. The application stores values in a database and, upon the users request, it will retrieve the data and plot this data on a line graph. The application is producing a line graph, but my issue is that it is producing one line graph for each piece of data that it retrieves from the database. So if the query returns 15 results, the application produces 15 graphs with one plot each. I want all of the data retrieved and plotted onto one graph. Below is my code. Can someone point me in the right direction?
try { Connection con = new DataConnection().connect(); ResultSet rs;
PreparedStatement retrieve = con.prepareStatement("SELECT row FROM table");
rs = retrieve.executeQuery();
while (rs.next())
{
String string = rs.getString(1);
double double = Double.parseDouble(string);
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(double, "Chart", "Data");
JFreeChart chart = ChartFactory.createLineChart("Graph", "Data", "Data", dataset, PlotOrientation.VERTICAL, true, false, false);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.black);
ChartFrame frame = new ChartFrame("Line Chart", chart);
frame.setVisible(true);
frame.setSize(450, 350);
}
}
Upvotes: 0
Views: 149
Reputation: 17971
So if the query returns 15 results, the application produces 15 graphs with one plot each. I want all of the data retrieved and plotted onto one graph.
Your code creates a new JFreeChart
instance for each row in your database query result set and that's why you get too many frames with charts opened. You have to create just a single JFreeChart
instance and add the data to its model as a series.
See this related Q&A: Multiple graphs in multiple figures using jFreeChart. There are also plenty of examples under jfreechart tag.
Upvotes: 2