在绘制图像时,jFrame GetGraphics在java中为null

我将图像绘制到jframe时出现nullexception错误。 我调试代码并检查图像和帧不是null但仍然在绘制图像到帧时抛出NULLexception。

请看一看 :

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()); } } 

NPE很可能来自这里:

 Graphics ga=jf.getGraphics(); 

根据文档 :

为此组件创建图形上下文。 如果此组件当前不可显示,则此方法将返回null。

1)不要使用Component#getGraphics作为其糟糕的实践/非持久性,并且除非组件可见,否则将返回null

2)使用JPanel并覆盖paintComponent(Graphics g)不要忘记调用super.paintComponent(g); 作为覆盖paintComponent第一个调用。

3)覆盖getPreferredSize()并返回正确的Dimension以适合正在绘制的图像。

4)将JPanel添加到框架中以使图像可见。

或者你也可以使用一个JLabelsetIcon(..)需要一个setIcon(..)调用,并添加到JFrame

以下是我的一些例子:

使用JPanel

  • 从C驱动器加载Java代码中的映像

  • 图像绘制适用于JFrame,但不适用于JPanel

  • 如何在框架中显示图像?

  • 将JPanel转换为JScrollPane中的图像

使用JLabel

  • 图像resize并在JPanel或JLabel中显示而不会降低质量