2012-06-28 72 views
8

我想用Java制作一个非常基本的游戏,但我在JFrame上显示图像时遇到了问题。它在过去为我工作,现在不是,我看不出我做错了什么。Java将ImageIcon添加到JLabel

我已经尝试打印当前的工作目录,并更改我的图像匹配的位置。这很可能是因为我的(档案寻找器或文件读取器等)没有问题,但我无法正确地将它(ImageIcon)添加到JLabelJFrame,从而无法获取图像。

这是我的代码...

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()

有人可以帮助我了解什么是错的。

+0

请看看这个例子中,[如何增加图象到你的项目](http://stackoverflow.com/questions/9864267/load-icon-image-exception/9866659#9866659)或请按照这些[步骤](http:// ga gandeepbali.uk.to/gaganisonline/webpages/makejareclipse.html) –

+0

我看了那些例子,他们没有帮助 – user1486826

+0

只需将你的图像放在你的.class文件旁边,并像这样使用ImageIcon image = new ImageIcon(getClass( ).getResource( “yourImage.extension”));.该链接必须有效,因为这是将图片放入项目中的正确方法。我希望你已经完成了所有提到的步骤! –

回答

12

你的问题就在这里:

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

您创建一个ImageIcon “形象”,但你创建一个 “字” 您的JLabel。

它应该是:

JLabel imagelabel = new JLabel(image); 
+0

对不起,在我的实际代码中他们是一样的,我忘了用图像替换字符。 – user1486826

3

尝试,

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

在教程看看 - How to use Icons

+0

我已经多次看过这个教程,我没有看到我做错了什么。 – 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

请为你的代码添加一些解释,并说明为什么OP需要你的代码;)。 –