问题描述
我正在尝试用Java做一个非常基础的游戏,但是我无法在JFrame
上显示图像.过去它对我有用,现在却不起作用,我看不到我做错了什么.
I am trying to make a very basic game with Java and I am having trouble displaying an image on a JFrame
. It has worked in the past for me and now is not, i can't see what I did wrong.
我尝试打印当前工作目录并更改获取图像的位置.问题很可能是没有获取图像,因为我(文件查找器或文件读取器或类似的东西)可以毫无问题地找到它,但是我无法正确地将它(ImageIcon
)添加到JLabel
中,或将其添加到JFrame
.
I have tried printing the current working directory and changing where I get my image to match that. It is likely that the problem is not getting the image, since my (filefinder or filereader or something like that) can find it without problems, but I cannot correctly add it (the ImageIcon
) to the JLabel
, or that to the 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()
.
有人可以帮助我了解问题所在吗.
Could someone please help me understand what is wrong.
推荐答案
您的问题出在这里:
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
JLabel imagelabel = new JLabel(character);
您创建了一个ImageIcon图像",但您使用字符"创建了JLabel.
You create an ImageIcon "image" but you create your JLabel with "character".
应该是:
JLabel imagelabel = new JLabel(image);
这篇关于Java将ImageIcon添加到JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!