我正在学习如何将图像添加到我的JFrame中。我在GUI方面是足够的,但我只是不明白为什么这不起作用。
我设置了数组,这样我就可以处理多个图像,以防您感到奇怪。
(1)我的问题是getClass().getResource("0.png");由于某种原因,它一直失败。当主(S.)去创建对象GUIv1,它在图像中失败.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);
}
}发布于 2013-01-29 23:14:46
使用getClass().getResource()时,图像必须与类文件GUIv1.class位于同一个位置,否则当null值传递给ImageIcon的构造函数时,会产生NPE。
如果您不确定类根位于何处(在本例中,图像应该位于何处),则可以显示以下结果:
System.out.println(getClass().getProtectionDomain().getCodeSource().getLocation());在你的构造函数中。
其次,不能将ImageIcon直接添加到JFrame容器中,因为它不是组件。您可以添加您的Jlabel,这是一个组件:
add(imagepanel[i]);https://stackoverflow.com/questions/14593766
复制相似问题