gpt4 book ai didi

java - java中绘制图像时jFrame GetGraphics为空

转载 作者:行者123 更新时间:2023-12-01 17:26:29 25 4
gpt4 key购买 nike

将图像绘制到 jframe 时出现空异常错误。我调试代码并检查图像和框架不为空,但在将图像绘制到框架时仍然抛出 NULL 异常。

请看一下:

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

根据docs :

Creates a graphics context for this component. This method will return null if this component is currently not displayable.

1) 不要使用 Component#getGraphics 作为其不好的做法/不持久,除非组件可见,否则将返回 null

2) 而是使用 JPanel 并覆盖 paintComponent(Graphics g) 不要忘记在第一次调用时调用 super.paintComponent(g);在重写的paintComponent中。

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

4) 将 JPanel 添加到框架中,以便图像当然可见。

或者,您也可以使用 JLabel,它只需要 setIcon(..) 调用即可添加到 JFrame .

以下是我的一些示例:

使用JPanel:

使用JLabel:

关于java - java中绘制图像时jFrame GetGraphics为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14632998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com