Eric Tamayo Eric Tamayo - 6 months ago 10
Java Question

JPanel being passed as null

I have a class DynamicDataDemo, which has a null pointer catch. However I don't understand why jPanel is being passed as null. It is initialized by netbeans as a border layout and size is also declared.

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;

}


In my main class I call

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


Any suggestions or solutions greatly appreciated!

Following code was generated by 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);

Answer

Just change your code like below. Hope it helps.

    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;
    }
Comments