[英]Why this GUI app does not show me the image?
我正在尝试用JFrame对象编写一个Java应用程序,该对象必须显示三个带有文本和图像的标签对象,我的文本“ North”和“ South”在执行时显示,但是我的图像却没有,即使我放了图像文件放入src文件夹。
package deitel9;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JFrame;
public class LabelDemo {
public static void main(String[] args)
{
//crate a label with a plain text
JLabel northLabel = new JLabel("North");
//crate an icon from an image so we can put it on a JLabel
ImageIcon labelIcon = new ImageIcon("maldive.jpg");
//crate a label with an Icon instead of text
JLabel centerLabel = new JLabel(labelIcon);
//create another label with an Icon
JLabel southLabel = new JLabel(labelIcon);
//set the label to display text (as well as an icon)
southLabel.setText("South");
//create a frame to hold the labels
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the labels to the frame; the second argument specifies
//where on the frame to add the label
application.add(northLabel,BorderLayout.NORTH);
application.add(centerLabel,BorderLayout.CENTER);
application.add(southLabel,BorderLayout.SOUTH);
application.setSize(300,300);
application.setVisible(true);
}//end main
}//end class LabelDemo
由于您的图片存储在存储LabelDemo
同一包中,请尝试执行此操作,
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("/deitel9/maldive.jpg").getFile());
要么
private String getImage() {
return getClass().getResource("/deitel9/maldive.jpg").getFile();
}
ImageIcon labelIcon = new ImageIcon(new LabelDemo().getImage());
要弄清楚在这种情况下您做错了什么,您只需致电
File file = new File ("maldive.jpg");
System.out.println(file.getAbsolutePath());
这将打印出它正在寻找文件的绝对路径,这可能会给您有关您做错了什么的指示。
当然,如果您知道如何使用调试器,则不需要第二行(技术上甚至不需要第一行,但这有点棘手;))
根据文档 ,您选择的ImageIcon
构造函数期望使用文件名或文件路径,因此图像需要在文件系统上,而不是在类路径上。
从指定的文件创建一个ImageIcon。 [...]指定的字符串可以是文件名或文件路径。
根据您的描述,您的项目布局如下所示
\---src
\---deitel9
LabelDemo.java
maldive.jpg
那么您应该能够将图像检索为位于类路径上的资源,如下所示:
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("maldive.jpg"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.