Java将ImageIcon添加到JLabel

Java将ImageIcon添加到JLabel,java,swing,jframe,jpanel,imageicon,Java,Swing,Jframe,Jpanel,Imageicon,我试图用Java制作一个非常基本的游戏,但在JFrame上显示图像时遇到了问题。这在过去对我有效,但现在不行,我看不出我做错了什么 我已经试着打印当前的工作目录,并更改获取图像的位置以匹配该目录。问题很可能是没有获取图像,因为我的(filefinder或filereader或类似的东西)可以毫无问题地找到它,但我无法将它(图像图标)正确地添加到JLabel,或者添加到JFrame 这是我的密码 JFrame frame = new JFrame("no image"); ImageIcon im

我试图用Java制作一个非常基本的游戏,但在
JFrame
上显示图像时遇到了问题。这在过去对我有效,但现在不行,我看不出我做错了什么

我已经试着打印当前的工作目录,并更改获取图像的位置以匹配该目录。问题很可能是没有获取图像,因为我的(filefinder或filereader或类似的东西)可以毫无问题地找到它,但我无法将它(图像图标
)正确地添加到
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
已设置为可见(true)
pack()


有人能帮我弄清楚哪里出了问题。

你的问题就在这里:

   ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
   JLabel imagelabel = new JLabel(character);
您创建了一个ImageIcon“image”,但创建了带有“character”的JLabel

应该是:

JLabel imagelabel = new JLabel(image);
试试看


查看教程-

抱歉,在我的实际代码中,它们是相同的,我忘记了用图像替换字符。我已经看过很多次教程,我看不出我做错了什么。请看一看这个示例,或者请遵循这些示例。我查看了这些示例,它们并没有帮助您简单地将图像放在.class文件旁边,并像这样使用ImageIcon image=newImageIcon(getClass().getResource(“yourImage.extension”);。这个链接必须起作用,因为它是将图像放入项目的正确方式。我希望你已经走过了书中提到的所有步骤!!只需将识别良好的代码从记事本复制到问题区域,然后选择所有代码并按CTL+K格式化即可。您实际上不必为每行按空格键八次。这会引发空指针异常。请添加一些有关代码的说明,以及OP需要代码的原因;)。
ImageIcon image = new ImageIcon("c:\\path\\image.png");
imagelabel = new JLabel(character, image, JLabel.CENTER);
frame.add(imagelabel);
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 
    } 
}