Search code examples
javavariablesargumentsimageicon

Java: Setting one ImageIcon equal to another


I'm trying to make xpic equal to vpic just like in the example below. When I try to compile this code I get the error : "The local variable xpic may not have been initialized"

ImageIcon xpic;
ImageIcon vpic;

    vpic = new ImageIcon(getClass().getResource("Images/picture.png"));     
    vpic = xpic;

Solution

  • I think that you have a typo because your code sets the vpic variable's reference, and then completely ignores what you set it to, and tries to set it to xpic (which is likely a null reference).

    In essence, what you're doing is equivalent to this:

    // both Strings are null
    String str1; 
    String str2; 
    
    // assign a String object to str1:
    str1 = "Hello";
    
    // but then ignore and in fact discard the String object, and 
    // re-set str1 to null by assigning it str2
    str1 = str2; //????
    

    You might want to change

    vpic = new ImageIcon(getClass().getResource("Images/picture.png"));     
    vpic = xpic;
    

    to

    vpic = new ImageIcon(getClass().getResource("Images/picture.png"));     
    xpic = vpic;