Java将ImageIcon添加到JLabel
我正在尝试使用Java制作一个非常基本的游戏,但我在JFrame
上显示图像时遇到问题。 它曾经为我工作过,现在不是,我看不出我做错了什么。
我已经尝试打印当前的工作目录并更改我的图像匹配的位置。 问题可能不是获取图像,因为我的(文件查找器或文件阅读器或类似的东西)可以毫无问题地找到它,但我无法正确地将它( 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()
。
有人可以帮我理解出了什么问题。
你的问题在于:
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png"); JLabel imagelabel = new JLabel(character);
您创建了一个ImageIcon“图像”,但您使用“character”创建了JLabel。
它应该是:
JLabel imagelabel = new JLabel(image);
尝试,
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 } }