I’m getting null exception error while drawing image to jframe.
i debug the code and check the image and frame is not null but still it is throwing NULL exception while drawing image to frame.
Please have a look :
public void run(){
try{
ObjectInputStream objVideoIn = new ObjectInputStream(serVideoIn);
byte[] imgbytes=null;
ByteArrayInputStream barrin=null;
JFrame jf = new JFrame();
Graphics ga=jf.getGraphics(); //Getting null exception
//Thread.sleep(10000);
jf.setVisible(true);
jf.setSize(400, 400);
while(true){
int index=0;
//Thread.sleep(300);
int size= (int)objVideoIn.readObject();
imgbytes = new byte[size];
barrin = new ByteArrayInputStream(imgbytes);
System.out.println("image size" + size);
//Thread.sleep(200);
while(index<size)
{
System.out.println("reading image");
int bytesread = objVideoIn.read(imgbytes, index, size-index);
if(bytesread<0){
System.out.println("error in receiving bytes yar");
}
index+=bytesread;
}
//barrin.read(imgbytes, 0, imgbytes.length);
barrin = new ByteArrayInputStream(imgbytes);
buffImg = ImageIO.read(barrin);
if(buffImg==null)
{
System.out.println("null received");
}
else {
System.out.println("image received");
**ga.drawImage(buffImg, 0, 0, null);**
}
}
}
}
catch(Exception ex)
{
System.out.println("error reading video" +ex.getMessage());
}
}
The NPE is likely coming from here:
as per docs:
1) Dont use
Component#getGraphicsas its bad pratice/not persistent and will returnnullunless component is visible.2) Rather use
JPaneland overridepaintComponent(Graphics g)dont forget to callsuper.paintComponent(g);as first call in overridenpaintComponent.3) Override
getPreferredSize()and return correctDimensions to fit image being drawn.4) add
JPanelto the frame for image to be visible of course.Alternatively You could also use a
JLabelwhich would require nothing more than asetIcon(..)call and be added added toJFrame.Here are some of my examples:
Using
JPanel:Loading image in Java Code from C drive
Image Drawing Works for JFrame, But Not JPanel
How to display an image in a frame?
Convert a JPanel to an image in a JScrollPane
Using
JLabel: