This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                2年前关闭。
            
                    
在这个程序中,我想在netbeans中以图像数组的形式加载图像。如果我读一张照片,该程序就可以工作。但是,当我使用循环加载图片时,在“ labelx.seticon(imageicon)”处出现错误。如您所见,我测试了图标是否为空并收到消息,它们不为空。任何帮助将不胜感激。错误我在主线程nullpointer异常中得到了一个错误。
                 谢谢

公共类Image_array2 {

    /**
     * @param args the command line arguments
     */
   public Image_array2()
    {
        photo();
    }
    public static void main(String[] args) {
        new Image_array2();
        int g=5;
        Image [] arrayimages = new Image[49];
        System.out.println("gamal" + g);

        // TODO code application logic here
    }
    public void photo()
    {
        //try{
        ImageIcon myicon;
        ImageIcon[] icons = new ImageIcon[3];
        JFrame frame = new JFrame();
        frame.setSize(900,900);
        JLabel[] labelx = new JLabel[3];
        JLabel mylabel = null;
        Image image;

         for(int i = 0 ; i<3;i++)
         {
             // image= new ImageIcon(this.getClass().getResource("src/image_array2/mycards/image"+i+".jpg")).getImage();
         ////  Image img = new ImageIcon(this.getClass().getResource("src/image_array2/mycards/image22.jpg")).getImage();
           //if(img == null)
              // System.out.println(" it is nothting");
          // else
               //System.out.println("it is okay");

         icons[i] = new ImageIcon("src/image_array2/mycards/image"+i+".jpg");
         myicon = icons[i];
         if(myicon == null)
               System.out.println(" it is nothting");
           else
               System.out.println("it is okay");
         labelx[i].setIcon(icons[i]);
         //label[0].setIcon(icons[i]);
        // mylabel.setIcon(myicon);
        // frame.add(label[i]); }
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      //  } catch(IOException e) {}
}
    }
}


screen shot of the program

最佳答案

labelx[i].setIcon(icons[i]);


调用此函数时,labelx [i]可能为null

10-06 01:49