Add a JFreeChart in to JPanel

Safari picture Safari · Oct 30, 2011 · Viewed 36.8k times · Source

if i have a my Jpanel and a my JFreeChart. How can I add this Chart in to the JPanel?

XYSeries series = new XYSeries("XYGraph");
   series.add(1, 1);
   series.add(1, 2);
   series.add(2, 1);
   series.add(3, 9);
   series.add(4, 10);

// Add the series to your data set
   XYSeriesCollection dataset = new XYSeriesCollection();
   dataset.addSeries(series);

// Generate the graph
   JFreeChart chart = ChartFactory.createXYLineChart(
   "XY Chart", // Title
   "x-axis", // x-axis Label
   "y-axis", // y-axis Label
   dataset, // Dataset
   PlotOrientation.VERTICAL, // Plot Orientation
   true, // Show Legend
   true, // Use tooltips
   false // Configure chart to generate URLs?
);

and now, how can i add chart in my JPanle?

Answer

Nicolas Modrzyk picture Nicolas Modrzyk · Oct 30, 2011

From an old java forums thread

JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new java.awt.BorderLayout());
 ..
ChartPanel CP = new ChartPanel(chart);
.. 
jPanel1.add(CP,BorderLayout.CENTER);
jPanel1.validate();