2

I am trying to implement a JFree Chart into my program, I am currently developing a Java Swing application. I want to display the chart into a panel inside the application. So, the table which I want to extract the data for the graph is as follows:


 -----------------------
| daily_total_statements|
 -----------------------
| Reference ID (PK)     |
| Value                 |
| Date                  |
 -----------------------

and the code i have used to implement the chart is:

    public void buidGraph(JPanel jp) {

        DefaultCategoryDataset dataset = createDataset();
        JFreeChart chart = ChartFactory.createLineChart(
                "Daily Progress",
                "Date", // X-Axis Label
                "Number of Members", // Y-Axis Label
                dataset
        );

        ChartPanel panel = new ChartPanel(chart);
        jp.add(panel);
    }

The dataset code i thought that would work and which i am a bit confused by it:

private DefaultCategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        try {
            String query = "SELECT `Value`, `Date` FROM `daily_total_statements` 
                            ORDER BY `Date` ASC";
            Connection c = MySQL_Database.getInstance().getConnection();
            PreparedStatement ps = c.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            String series2 = "Daily progress";
            while (rs.next()) {
                dataset.addValue(rs.getInt(1), series2, rs.getString(2));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Problem creating chart! " + e.getMessage());
        }
        return dataset;
    }

I am using a singleton class for the database as you can see. The problem is that the chart is not displayed at all it's just an empty panel. Please if you could help! Sorry for the bad formatting and language!

  • I tried it as a frame and it works perfectly, it shows the chart and exact values! But still can't figure out how to add it into a panel. – Xhuliano Tatazi Jun 29 '20 at 13:11
  • Where are you calling `buildGraph`. Try to use `BorderLayout` for the panel you are passing to `buildGraph`. Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – weisj Jun 29 '20 at 13:53
  • @weisj I use it on the GUI and just call it on the GUI constructor. It doesn't show anything, no errors no visual representation. I tried it with `BorderLayout.CENTER` but it still didn't do a thing. I have used drag&drop method with Netbeans and the GUI code is auto-generated, as i said if i make it as a frame it works perfectly but when I try the panel it won't display nothing inside that panel. – Xhuliano Tatazi Jun 29 '20 at 15:04
  • Please provide a [minimal working example](https://stackoverflow.com/help/minimal-reproducible-example) otherwise there is no way for someone to help you. Because the graph is displayed when directly added to the frame I assume your graph creation logic is fine. Because "when I try the panel it won't display nothing inside that panel" I am assuming you are using an incorrect layout manager or you are missing to add the panel to the actual frame. – weisj Jun 29 '20 at 16:29
  • @weisj Yes sure, I have uploaded a simple version of the operation I want to perform. You can find it [here](https://github.com/xhuliano98/GraphTest/blob/master/Test.jar) I have tried with different layouts on the panel but still same result. – Xhuliano Tatazi Jun 29 '20 at 17:38
  • 1
    A `ChartPanel` _is a_ `JPanel`; just add it to your frame. See also [`JDBCXYDataset`](https://stackoverflow.com/search?q=%5Bjfreechart%5D+JDBCXYDataset). – trashgod Jun 30 '20 at 18:04
  • You can [answer your own question](http://meta.stackoverflow.com/q/17463/163188). – trashgod Jul 01 '20 at 21:15

1 Answers1

1

Because a ChartPanel is a JPanel, you can simply add it to your frame, as shown below. The frame's default layout is BorderLayout and the default constraint is CENTER. Moreover,

  • Use one of the approaches seen here to establish the chart's initial size.
  • Use an appropriate layout to control resize behavior.
  • Consider using JDBCXYDataset, illustrated here

Graph

import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

public class GraphTest extends JFrame {

    public GraphTest() {
        initComponents();
    }

    private void initComponents() {
        add(buildLineGraph());
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(GraphTest::new);
    }

    public ChartPanel buildLineGraph() {
        DefaultCategoryDataset dataset = createLineGraphDataset();
        JFreeChart chart = ChartFactory.createLineChart("Daily Progress",
            "Day", "Value", dataset, PlotOrientation.VERTICAL, true, true, false);
        return new ChartPanel(chart) {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(640, 480);
            }
        };
    }

    private DefaultCategoryDataset createLineGraphDataset() {
        // TODO: use JDBCXYDataset
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(1, "Result", "Mon");
        dataset.addValue(5, "Result", "Tue");
        dataset.addValue(7, "Result", "Wed");
        return dataset;
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045