JPanel作为null传递

时间:2016-05-23 22:42:11

标签: java swing netbeans

我有一个类DynamicDataDemo,它有一个空指针catch。但是我不明白为什么jPanel被传递为null。它由netbeans初始化为边框布局,并且还声明了大小。

public DynamicDataDemo(final String title){
this(title,null);
}    

public DynamicDataDemo(final String title, JPanel panel){
super(title);
setContentPane(initContents(panel));
}

public JPanel initContents(JPanel contentPanel){
    if (contentPanel == null){
        System.out.print("You are Here");
        contentPanel = new JPanel(new BorderLayout());
    }


    this.series = new TimeSeries("Data", Millisecond.class);
    final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series);
    final JFreeChart chart = createChart(dataset);

    final ChartPanel chartPanel = new ChartPanel(chart);
    contentPanel.setLayout(new BorderLayout());
    contentPanel.removeAll();
    contentPanel.add(chartPanel, BorderLayout.CENTER);
    contentPanel.validate();
    return contentPanel;              

}

在我的主要课程中,我打电话给

Final DynamicDataDemo dynamicPlot = new DynamicDataDemo("nameOfPlot", jPanel1);

非常感谢任何建议或解决方案!

以下代码由netBeans生成:

private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();

    jPanel1.setBackground(new java.awt.Color(0, 0, 0));
    jPanel1.setLayout(new java.awt.BorderLayout());

    jPanel2.setBackground(new java.awt.Color(0, 0, 0));
    jPanel2.setLayout(new java.awt.BorderLayout());
}

private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration                   

我编写的代码:

final DynamicDataDemo dynamicEyePlot = new DynamicDataDemo("Eye Height", jPanel1);
final DynamicDataDemo dynamicGainPlot = new DynamicDataDemo("Gain",jPanel2);

1 个答案:

答案 0 :(得分:1)

只需更改您的代码,如下所示。希望它有所帮助。

    public DynamicDataDemo(final String title) {
        this(title,null);
    }

    public DynamicDataDemo(final String title, JPanel panel) {
        super(title);
        setContentPane(initContents(panel));
    }

    public JPanel initContents(JPanel contentPanel) {
        if (contentPanel == null) {
            contentPanel = new JPanel(new BorderLayout());
        }
        this.series = new TimeSeries("Data", Millisecond.class);
        final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series);
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(800, 400));
        contentPanel.setLayout(new BorderLayout());
        contentPanel.add(chartPanel);
        return contentPanel;
    }