Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
JFree Chart with data from MySQL Database into a JPanel

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!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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;
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda