简体   繁体   中英

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

}


@SuppressWarnings("unchecked")
// <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)

It looks like you are trying to add a new view component, ie 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.

图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM