这是我第一次尝试使用 GUI,我正在尝试设置 JButton 的图标。无论我如何编码,我都会得到一个 NPE。我已经标记了发生 NPE 的行。我已经成功地将 URL 传递给 setIcon 方法,但它从不影响 GUI。我也尝试过使用 Icon 而不是 Image Icon 的代码,没有任何变化。任何建议都会非常有帮助。谢谢。
static Random roll = new Random();
handCard1 = new javax.swing.JButton(); //this has been initialized through a series of methods that initialized the GUI
public static void main(String args[])
{
yourHand.setCard1(rollForCard.getCard()); //randomly set to fire, water or wind
if (yourHand.getCard1().equals("fire"))
handCard1.setIcon(SetIcon.setFireIcon()); //NPE here
//I also tried a simple handCard1.setIcon(fire);
//with this before the main ImageIcon fire = new ImageIcon("fire.jpg");
}//end main
设置图标...
import javax.swing.ImageIcon;
public class SetIcon
{
public static ImageIcon setFireIcon()
{
ImageIcon fire = (new ImageIcon("fire.jpg"));
//I have also tried: ImageIcon fire = (new javax.swing.ImageIcon(getClass().getResource("fire.jpg")));
//and: ImageIcon fire = new ImageIcon(getClass().getResource("fire.jpg")));
return fire;
}
}