Java向JLabel添加ImageIcon

8

我正在尝试使用Java制作一个非常基本的游戏,但是我在显示图像时遇到了问题。这在过去曾经成功过,但现在不行了,我不知道哪里出了问题。

我已经尝试打印当前工作目录并更改获取图像的位置以匹配它。由于我的(文件查找器或文件读取器或类似的东西)可以毫无问题地找到它,因此很可能问题不在于获取图像,而是不能正确地将其(ImageIcon)添加到JLabel中,或者将其添加到JFrame中。

这是我的代码...

JFrame frame = new JFrame("no image");
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
JLabel imagelabel = new JLabel(image);
frame.add(imagelabel);

JFrame已经执行了setVisible(true)pack()方法。

请问有人可以帮我理解出错的原因吗?


请查看这个例子,如何将图像添加到您的项目 或者请按照这些步骤 - nIcE cOw
只需将您的图像放在.class文件旁边,然后像这样使用它:ImageIcon image = new ImageIcon(getClass().getResource("yourImage.extension"));。链接必须有效,因为这是将图像放入项目中的正确方法。我希望您已经按照提到的所有步骤进行了操作! - nIcE cOw
只需从记事本中复制漂亮的缩进代码到问题区域,然后选择所有代码并按下CTL + K进行格式化。您实际上不必为每行按八次空格键。 - nIcE cOw
抛出空指针异常 - user1486826
我自己解决了,解决方案是将图像命名为“新位图图像”。我认为由于某种原因它认为我没有指定文件名,并且正在寻找默认文件名。 - user1486826
显示剩余3条评论
3个回答

12

你的问题出在这里:

   ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
   JLabel imagelabel = new JLabel(character);

你创建了一个名为"image"的ImageIcon,但是你使用"character"来创建了JLabel。

应该这样:

JLabel imagelabel = new JLabel(image);

抱歉,在我的实际代码中它们是相同的,我忘记用图像替换字符了。 - user1486826

2

请尝试,

ImageIcon image = new ImageIcon("c:\\path\\image.png");
imagelabel = new JLabel(character, image, JLabel.CENTER);
frame.add(imagelabel);

请查看教程 - 如何使用图标


我已经多次查看了教程,但我没有看出我错在哪里。 - user1486826

-1
import javax.awt.*; 
import java.awt.*; 
import java.awt.event*; 

//class name image 
class image { 
    image() 
    //constructor { 
        Frame f=new Frame("Image"); 
        //Frame
        f.setSize(500,500); 
        f.setVisible(true); 
        Panel p =new Panel(); 
        //Panel 
        f.add(p); 
        p.addLayout(null); 
        ImageIcon ii=new ImageIcon("set your image path"); 
        //ImageIcon is used to image Display . 
        Label l =new Label(ii); 
        p.add(ii); 
        p.setBounds(set you bounds); 
        //Like that(20,20,500,40); 
    } 

    public static void main(String [] args) { 
        image obj = new 
    } 
}

2
请在您的代码中添加一些说明,解释为什么需要使用您的代码。;) - shA.t

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接