我想测试一个带有简单png图像的程序.我写了一个简短的程序来做到这一点,但我似乎无法让路径正确.我已经检查,再次检查,重新检查,并检查了我的路径名称四倍,但没有正确,但无论我做什么,这个图像都不会显示.我使用了Oracle在
ImageIcon文档(creaetImageIcon())中编写的一个简短类来完成此任务,但它似乎没有帮助.我将在下面发布整个程序,因为它很短.
package practiceImages;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ImageIconGUITest {
public static void main(String[] args) {
ImageIconGUITest gui = new ImageIconGUITest();
gui.display();
}
private 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;
}
}
private void display() {
JFrame frame = new JFrame();
JLabel label = new JLabel(createImageIcon(
"Users/Evan/javaItems/Sprites_and_Other_Art/green.png", "the color green"));
frame.add(BorderLayout.CENTER, label);
frame.setSize(500, 500);
frame.setVisible(true);
}
}