I am creating a swing application and would like to add a JfreeChart to a Jpanel. I have created a method where I am created the Chart as one can see below:
Created a global variable:
JFreeChart chart;
Method for creating the chart:
public void createChart(){
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
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?
);
}
I then created the ChartPanel and added it to the JPanel which is attached to a JFrame:
JPanel reporting = new JPanel();
ChartPanel CP = new ChartPanel(chart);
reporting.add(CP,BorderLayout.CENTER);
reporting.validate();
reporting.setBounds(47, 59, 921, 439);
frame.getContentPane().add(reporting);
reporting.setLayout(new BorderLayout(0, 0));
I also created a button with an action listener to it where I call the method as one see below:
JButton btnReporting = new JButton("Reporting");
btnReporting.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
createChart();
}
});
For some reason the chart isn't showing when I click on the button.
revalidate
andrepaint
on the frame to update the UI. – MadProgrammerchart
is the global one and it is still not showing. – mario.borgrevalidate
andrepaint
the JPanel ? – mario.borgXYSeriesCollection
and changed theXYSeries
loaded in it. There are data change events fired after you modify it so I never needed to call repaint(). – Appak