[英]jFrame GetGraphics is null in java While Drawing image
I'm getting null exception error while drawing image to jframe. 将图片绘制到jframe时出现null异常错误。 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. 我调试代码并检查图像和框架是否不为null,但在将图像绘制到框架时仍然抛出NULL异常。
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: NPE可能来自这里:
Graphics ga=jf.getGraphics();
Creates a graphics context for this component. 为此组件创建图形上下文。 This method will return null if this component is currently not displayable. 如果此组件当前不可显示,则此方法将返回null。
1) Dont use Component#getGraphics
as its bad pratice/not persistent and will return null
unless component is visible. 1)不要使用Component#getGraphics
作为其不好的实践/不是持久的,除非组件可见,否则将返回null
。
2) Rather use JPanel
and override paintComponent(Graphics g)
dont forget to call super.paintComponent(g);
2)宁可使用JPanel
并覆盖paintComponent(Graphics g)
不要忘记调用super.paintComponent(g);
as first call in overriden paintComponent
. 作为覆盖的paintComponent
第一个调用。
3) Override getPreferredSize()
and return correct Dimension
s to fit image being drawn. 3)重写getPreferredSize()
并返回正确的Dimension
以适合要绘制的图像。
4) add JPanel
to the frame for image to be visible of course. 4)将JPanel
添加到框架中以使图像当然可见。
Alternatively You could also use a JLabel
which would require nothing more than a setIcon(..)
call and be added added to JFrame
. 另外,您也可以使用JLabel
, setIcon(..)
需要setIcon(..)
调用并将其添加到JFrame
。
Here are some of my examples: 这是我的一些示例:
Using JPanel
: 使用JPanel
:
Image Drawing Works for JFrame, But Not JPanel 图像绘图适用于JFrame,但不适用于JPanel
Convert a JPanel to an image in a JScrollPane 将JPanel转换为JScrollPane中的图像
Using JLabel
: 使用JLabel
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.