我正在尝试在我的应用程序中显示图像...
picture = new JLabel("No file selected");
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
scrollPane.setViewportView(picture);
ImageIcon icon = new ImageIcon("map.jpg");
picture.setIcon(icon);
if (picture.getIcon() != null) // to see if the label picture has Icon
picture.setText("HERE IS ICON");
当我运行该代码时,仅显示"这里是图标"文本。抱歉,如果这个问题听起来很愚蠢,但我真的不知道为什么图像图标不显示:(
你需要
确保map.jpg作为一个文件存在。如果要确定(仅用于测试目的),请尝试使用完整路径。按照您拥有它的方式,路径是相对于应用程序的启动目录的。
您可以仔细检查它是否存在:
System.out.println(new java.io.File("map.jpg").exists());
你可以这样做:
ImageIcon icon = createImageIcon("map.jpg", "My ImageIcon");
if (icon != null) {
JLabel picture = new JLabel("HERE IS ICON", icon, JLabel.CENTER);
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
scrollPane.setViewportView(picture);
}
方法(在前面的代码片段中使用)查找指定的文件并返回该文件的 ImageIcon,如果找不到该文件,则返回 null。下面是一个典型的实现:
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
文件映射.jpg可能与 java 文件不在同一个包(文件夹)中。检查一下。