2016-05-23 64 views
0

我有一個類DynamicDataDemo,它有一個空指針捕獲。但我不明白爲什麼jPanel被傳遞爲null。它由netbeans初始化爲邊界佈局,並且還聲明瞭大小。JPanel作爲NULL傳遞

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); 
+0

您JPANEL1爲空,顯示你來自哪裏, –

+0

有JPANEL1我怎麼證明我來自哪裏得到JPANEL1?我從宣佈jPanel1的主類中傳遞它。 – Emunzy

+0

顯示您從哪裏調用DynamicDataDemo,以及從哪裏獲取您傳入的面板。我看到的全部是新的DynamicDataDemo(「nameOfPlot」,jPanel1);但我想看看jPanel1在哪裏創建或引用 –

回答

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; 
    } 
+0

該解決方案適用於捕獲null異常,並允許我的代碼進行編譯。不過,我想解決爲什麼jPanel1被傳遞爲null。儘管感謝解決方案。 – Emunzy