Java:设置一个ImageIcon等于另一个



我试图使xpic等于vpic,就像下面的例子一样。当我尝试编译这段代码时,我得到错误:"局部变量xpic可能尚未初始化"

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

我认为你有一个打字错误,因为你的代码设置了vpic变量的引用,然后完全忽略了你设置它的内容,并尝试将其设置为xpic(这可能是null引用)。

本质上,你所做的等同于:

// 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; //????

您可能想要更改

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

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

最新更新