Reputation: 189
When a button is clicked, my graph()
method needs to loop the following line:
ddataset.setValue(new Double(unitsSold), cat, brand + " " + name);
The number of loops is based on the number of items in the category column of my database. The first item is "Cables" which has seven items in it. I want to store each of these items into an array (from the database) to then display all of them on a single bar chart using a for loop
. What is the correct syntax to do this?
Here is my graph()
method coding:
public void graph()
{
//variable to get the row count
int x = 0;
try
{
//declaring the type of category in the column
String text = "Cable";
//Select statement getting the row count
String sql = "select count(category) from dbsales where category ='" + text + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/salventri","root","password");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
//setting 'x' with the row count
x = rs.getInt("count(category)");
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
//loop the data according to x value
for(int i = 0; i < x; i++)
{
ddataset.setValue(new Double(unitsSold), cat, brand + " " + name);
}
JFreeChart chart = ChartFactory.createBarChart3D("Annual Sales Performance", cat, "Number of Units Sold", ddataset);
chart.getTitle().setPaint(Color.RED);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
ChartFrame frame2 = new ChartFrame("Annual Sales", chart);
frame2.setVisible(true);
frame2.setSize(450,350);
}
Upvotes: 2
Views: 103
Reputation: 7018
This was the only thing that made sense to me. There is no need for the count query or to put the category in the data since the whole chart is for that category. The year does need to be in the data unless you want to sum over all years.
PreparedStatement stmt = con.prepareStatement("select * from dbsales where category=?");
stmt.setString(1, text);
ResultSet rs = stmt.executeQuery();
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
while (rs.next()) {
ddataset.setValue(new Double(rs.getDouble("usold")),
rs.getString("pbrand") + " " + rs.getString("pname"),
rs.getString("syear"));
}
JFreeChart chart = ChartFactory.createBarChart3D("Annual Sales Performance", text, "Number of Units Sold", ddataset);
chart.getTitle().setPaint(Color.RED);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
ChartFrame frame2 = new ChartFrame("Annual Sales", chart);
frame2.setVisible(true);
frame2.setSize(450, 350);
Should produce something like this:
Upvotes: 2