在java中如何加载一张图片?
首先,更改此行:
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
对此:
image = ImageIO.read(getClass().getResource("/resources/icon.gif"));
可以在此线程上找到有关这两种方法之间的区别的更多信息 - 加载资源的不同方法
对于Eclipse:
对于NetBeans:
对于IntelliJ IDEA:
getClass().getResource("/resources/images/myImage.imageExtension");
Shift+ F10
如果你手动进行操作:
快速参考代码示例(尽管需要更多详细信息,但需要一些额外的说明链接):
package swingtest; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; /** * Created with IntelliJ IDEA. * User: Gagandeep Bali * Date: 7/1/14 * Time: 9:44 AM * To change this template use File | Settings | File Templates. */ public class ImageExample { private MyPanel contentPane; private void displayGUI() { JFrame frame = new JFrame("Image Example"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); contentPane = new MyPanel(); frame.setContentPane(contentPane); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } private class MyPanel extends JPanel { private BufferedImage image; public MyPanel() { try { image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg")); } catch (IOException ioe) { ioe.printStackTrace(); } } @Override public Dimension getPreferredSize() { return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight()); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, this); } } public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { new ImageExample().displayGUI(); } }; EventQueue.invokeLater(runnable); } }