【问题标题】:jFrame GetGraphics is null in java While Drawing imagejava中的jFrame GetGraphics在绘制图像时为空
【发布时间】:2013-01-15 23:31:38
【问题描述】:

在将图像绘制到 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? (请不要只给我们行号...)
  • 这里:图形 ga=jf.getGraphics(); //获取空异常

标签: java image swing graphics jframe


【解决方案1】:

NPE 很可能来自这里:

Graphics ga=jf.getGraphics();

根据docs:

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

1) 不要使用Component#getGraphics 作为它的坏习惯/不持久,除非组件可见,否则将返回null

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

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

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

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

这是我的一些例子:

使用JPanel

使用JLabel

【讨论】:

    猜你喜欢
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    相关资源
    最近更新 更多