Java:将一个ImageIcon设置为另一个

时间:2014-07-05 00:52:05

标签: java variables arguments imageicon

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

ImageIcon xpic;
ImageIcon vpic;

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

1 个答案:

答案 0 :(得分:4)

我认为您有一个拼写错误,因为您的代码设置了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;