Dương Anh Khoa Dương Anh Khoa - 1 year ago 124
Java Question

Adding ChartPanel to jPanel not working

I got this panel:

public class StripchartPanel extends javax.swing.JPanel {
public StripchartPanel() {
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();

// 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?
ChartPanel CP = new ChartPanel(chart);
this.add(CP, BorderLayout.CENTER);


// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

setLayout(new java.awt.BorderLayout());
}// </editor-fold>


It does not show the chart when I add this panel to a jFrame.

I'm pretty confident that the problem is lie within the jPanel implementation.

Can someone give me some pointer. (Other panels does not seem to have a problem until now)

Answer Source

It looks like you are trying to add a new view component, i.e. a ChartPanel, to an existing container dynamically. Although it is technically possible to add a new component at runtime using add(), validate() and repaint(), the result scales poorly as the application evolves.

Alternatively, add the view component before invoking pack() on the enclosing container, as shown here, and update the corresponding model as new data arrives; the listening view will update itself in response. A related example showing multiple strip charts is shown here and pictured below. If necessary, you can always replace the chart panel's enclosed chart using setChart(). Finally, consider CardLayout if different charts need different controls.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download