【问题标题】:getClass().getResource() Exception?getClass().getResource() 异常?
【发布时间】:2013-01-13 15:56:54
【问题描述】:

我正在尝试学习如何将图像添加到我的 JFrame。我在 GUI 方面已经足够了,但我根本无法理解为什么这不起作用。

我已经设置了数组,所以我可以做多个图像,以防你想知道。

(1) 我的问题是 getClass().getResource("0.png");由于某种原因,这一直失败。当 main(S...) 去创建对象 GUIv1 时,它在 image[0].....0.png") 中失败;

不知道为什么,我正在使用 eclipse,并且图像就在我的班级所在的默认包中。有什么需要吗?

(2) 这里似乎也有问题,但这不是第一个异常的原因,我也很感激这个问题的答案。

(如果代码字体有误,我深表歉意,这是我第一次来这里)。

import java.awt.*;
import javax.swing.*;

public class GUIv1 extends JFrame{

private static int tilesnum = 2;
private static ImageIcon[] image = new ImageIcon[tilesnum + 2];
private static JLabel[] imagepanel = new JLabel[tilesnum + 2];

public GUIv1() {
    setLayout(new FlowLayout());

    image[0] = new ImageIcon(getClass().getResource("0.png"));     //HERE (1)
    image[1] = new ImageIcon(getClass().getResource("1.png"));
    image[2] = new ImageIcon(getClass().getResource("2.png"));
    image[3] = new ImageIcon(getClass().getResource("3.png"));

    for(int i = 0; i < tilesnum + 2; i++) {
        imagepanel[i] = new JLabel(image[i]);
        add(image[i]);                                         //HERE (2)
    }

}

public static void main(String[] args) {

    GUIv1 selectorframe = new GUIv1();  
    selectorframe.setTitle("MapEditor v2");
    //JFrame mainframe = new JFrame("MapEditor v2");    
    selectorframe.pack();
    selectorframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    selectorframe.setVisible(true);
}   
}

【问题讨论】:

  • 什么异常? GetResource() 不会抛出异常,它返回 null。如果您遇到异常,则它在您的代码中。
  • 这个answer 可能会引导您朝着需要的方向前进 :-)

标签: java swing components imageicon getresource


【解决方案1】:

当使用getClass().getResource()时,你的图片必须和你的类文件GUIv1.class位于相同的位置,否则当null的值被传入ImageIcon的构造函数时会产生NPE

如果您不确定类根在哪里(在这种情况下,图像应该位于哪里),您可以显示以下结果:

System.out.println(getClass().getProtectionDomain().getCodeSource().getLocation());

在你的构造函数中。

其次,您不能将ImageIcon 直接添加到您的JFrame 容器中,因为它不是一个组件。你可以添加你的Jlabel,这一个组件:

add(imagepanel[i]);

【讨论】:

  • 另外,你需要确保资源已经被实际包含(即如果它是一个 Jar 资源,资源需要包含在 Jar 中。如果它是一个类的目录,再次,需要包含资源)+1
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 2014-04-05
  • 2014-01-20
  • 1970-01-01
  • 2021-12-15
  • 2014-12-07
  • 2016-05-27
  • 1970-01-01
相关资源
最近更新 更多