我用如下方法在eclipse中用一个图片来显示按钮,在eclipse中可以显示图片,但是导出之后就不能显示图片了,这是为什么呀?
ImageIcon imgCenter = new ImageIcon("src/1/1.jpg");
JButton jbtInquest = new JButton(imgCenter);
ImageIcon imgCenter = new ImageIcon("src/1/1.jpg");
JButton jbtInquest = new JButton(imgCenter);
或者放在jar包外面像这么访问new ImageIcon("1/1.jpg");
ImageIcon imgCenter = new ImageIcon(getClass().getResource("/1/1.jpg"));
将jar包以压缩文件方式打开后的目录为根目录进行相对查找
委托类加载器去寻找这个URL的资源,他会去classpath环境变量里找。
这个是反射机制,就是让程序可以访问它本身,你既然把它打到JAR包里,就要用反射机制。
但是我要是不打到JAR包里,而是直接把目录复制出来,不使用这个反射机制也是不显示图片的,这是为什么呀?
你要保证目录正确,如果你代码里写的是new ImageIcon("src/1/1.jpg"),就要在已经被编译完成过的.class文件所在的那层目录里有src目录,src里面有个1目录,1里面有个1.jpg文件。目录即不能错,也不能在.java源文件所在的目录下。有时候Eclipse的目录结构是让人搞不懂的,你可以手动做一下。比如先编译以下源文件。import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;public class Main extends JFrame {
public Main() {
ImageIcon image = new ImageIcon("image.jpg");
JButton button = new JButton(image);
button.setPreferredSize(new Dimension(200, 200));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(button);
this.setResizable(false);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new Main();
}}然后把编译好的Main.class文件找到,放到你想要的目录。然后把image.jpg这个图片放到和这个Main.class文件相同的目录。然后用命令提示符进到所在目录执行 java Main 。这样就可以了。