eclipse获取图片路径

注意:在命令行下,我们可以直接用ImageIcon i = new ImageIcon( “pic.jpg”);直接加载当前目录下的图片

但在eclipse中,源文件路径src和编译路径bin不是同一个,如果在eclipse写这句,它会在项目路径也就是src的上一级目录找这个文件,会出现找不到的异常。(要写成src/Images/a.jpg)
 

可以:

一、使用类加载器的路径

使用方法:

String path = this.getClass().getClassLoader().getResource(“.”).getPath();

或者

String path = 类名.class.getClassLoader().getResource(“.”).getPath();

前者不能写在静态代码块中,后者可以

但:这种方法有缺陷,代码可以在IDE中运行,打包成jar之后不能访问图片,所以可以考虑把获取类加载器的上一级路径,然后把图片存到jar的外部


public class Test extends JFrame {
 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
 
	public Test(String str) {
		super(str);
		JPanel p = new JPanel();

		// 获得类加载器路径
		String path = this.getClass().getClassLoader().getResource(".").getPath();
		System.out.println(path);
		// 后面的pic.jpg直接粘贴到eclipse的src目录下或者netbeans的源包目录下
		ImageIcon i = new ImageIcon(path + "pic.jpg");
 
		JLabel l = new JLabel(i);
		l.setBounds(0, 0, 800, 600);
		getLayeredPane().add(l, new Integer(Integer.MIN_VALUE));
		p = (JPanel) this.getContentPane();
		p.setOpaque(false);
		p.setLayout(new FlowLayout(FlowLayout.CENTER, 110, 30));
	}
 
	public static void main(String[] args) {
		Test dl = new Test("Test");
		dl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		dl.setLocation(400, 200);
		dl.setSize(800, 600);
		dl.setVisible(true);
	}
 
}

二、按流读取


import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
 
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
public class Test extends JFrame {
 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
 
	public Test(String str) {
		super(str);
		JPanel p = new JPanel();
 
		ImageIcon i = new ImageIcon(this.getImage("/pic.jpg"));

		JLabel l = new JLabel(i);
		l.setBounds(0, 0, 800, 600);
		getLayeredPane().add(l, new Integer(Integer.MIN_VALUE));
		p = (JPanel) this.getContentPane();
		p.setOpaque(false);
		p.setLayout(new FlowLayout(FlowLayout.CENTER, 110, 30));
	}
 
	public BufferedImage getImage(String str) {
		BufferedImage image = null;
		try {
			InputStream is = this.getClass().getResourceAsStream(str);
			image = ImageIO.read(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}
 
	public static void main(String[] args) {
		Test dl = new Test("Test");
		dl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		dl.setLocation(400, 200);
		dl.setSize(800, 600);
		dl.setVisible(true);
	}
 
}

 

    原文作者:wangqianqianya
    原文地址: https://blog.csdn.net/wangqianqianya/article/details/84500369
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞