要加载图像,您可以使用此方法:
ImageIcon loadImageIcon(String name) {
URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
其中参数name具有以下约束:
- 如果名称以
/ 开头,则资源的绝对名称是名称中/ 之后的部分。
- 否则,绝对名称的格式如下:
modified_package_name/name,
其中modified_package_name 是此对象的包名,其中/ 替换为.。
详情请见description of getResource(String name) method。
例如,如果您将此方法放在MyPanel.java 文件中,并且您有以下包结构
swing/
| - panel/
| | - MyPanel.java
| - resources/
| - my_image.jpg
可能比name参数可能
../resources/my_image.jpg 或 /swing/panel/resources/my_image.jpg,
但既不是swing/panel/resources/my_image.jpg,也不是/resources/my_image.jpg。
更新:
这是一个工作示例。在 NetBeans UI Designer 中,您可以进行模拟。
package swing.panel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
/** Returns an ImageIcon, or null if the path was invalid. */
private static ImageIcon loadImageIcon(String path) {
URL imgURL = ImagePanel.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
ImagePanel panel =
new ImagePanel(loadImageIcon("../resources/image.png").getImage());
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}