Connect with Expertise | Find Experts, Get Answers, Share Insights

how to solve NullPointerException in java swing

 
Join Date: Jan 2010
Location: chennai
Posts: 1
#1: Jan 30 '10
import javax.swing.*;
import java.awt.*;

public class RegionFrame extends JFrame
{
JLabel lblRegName=null;
JLabel lblDistName=null;
JLabel lblRegionForm=null;
JLabel lblStatName=null;
JTextField txtRegName=null;
JTextField txtDistName=null;
JButton butAdd=null;
JButton butUpdate=null;
JComboBox cmbSta=null;


public RegionFrame()
{
Container cont=getContentPane();

cont.setLayout(null);

lblRegionForm=new JLabel("Region");

lblDistName=new JLabel("District Name");
lblRegName=new JLabel("Region Name");
txtDistName=new JTextField(25);
txtRegName=new JTextField(25);
butAdd=new JButton("Add");
butUpdate=new JButton("Update");
cmbSta=new JComboBox();

cont.add(lblDistName);
cont.add(txtDistName);
lblDistName.setBounds(50,50,120,25);
txtDistName.setBounds(180,50,150,25);

cont.add(lblRegName);
cont.add(txtRegName);
lblRegName.setBounds(50,150,120,25);
txtRegName.setBounds(180,150,150,25);


cont.add(lblStatName);
cont.add(cmbSta);
lblStatName.setBounds(50,150,120,25);
cmbSta.setBounds(180,150,150,25);

cont.add(butAdd);
cont.add(butUpdate);
butAdd.setBounds(100,125,80,25);
butUpdate.setBounds(200,125,80,25);

setVisible(true);
pack();
setSize(600,400);
}
public static void main(String ar[])
{
new RegionFrame();
}
}







Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:621)
at java.awt.Container.add(Container.java:307)
at RegionFrame.<init>(RegionFrame.java:44)
at RegionFrame.main(RegionFrame.java:60)

E
C
 
Join Date: Nov 2007
Posts: 153
#2: Jan 30 '10

re: how to solve NullPointerException in java swing


You read these stack traces from the top down and once you get to a line that mentions your code you have a place to start looking for the bug.

"at RegionFrame.<init>(RegionFrame.java:44)" means that the error originated on the 44th line of the code you posted. Find this line.

The exception itself - "Exception in thread "main" java.lang.NullPointerException" - means that you have tried to dereference some variable whose value was null. This can come about for several reasons: you use the dereference (dot) operator on a variable whose value is null, or you make an array access on an array variable whose value is nulll, or you passa variable whose value is null to some other method that only accepts non null arguments.

So go to line 44 and check the two variables you find. Are either of them null? (You can check this with System.out.println()). Once you have found the null variable ask yourself: where did I mean to give that variable a nonnull value? And why didn't that happen?
Reply