Java 项目在 Eclipse 上工作但在导出到可运行的 jar 文件时不工作

标签 java eclipse jar jlabel

我在将我的 java 文件导出到可运行的 jar 文件时遇到问题。 在 Eclipse 中它工作正常,但是当我导出它时,它不起作用。

我已经尝试过 (java -jar MyJar.jar) 来获取日志,但它说 “无法访问 jar 文件”

我认为问题是因为这个:

java.net.URL logoOneUrl = getClass().getResource("/logo.png"); //already tried without the "/" and it doesn't work withouth the "/"
Icon logoOne = new ImageIcon(logoOneUrl)

因为当我将它放在注释 // 中时,当我导出它时它运行但没有图像。

我也试过这种方式: java.net.URL logoScience = getClassLoader().getResource("logo.png"); 但它也不起作用。 我究竟做错了什么? 如何在 JLabel 上导出带有图像的可运行 jar 文件?

(这是我的 JLabel 上的内容) JLabel lblImgLogin = new JLabel(logoOne);

更新

ImageIcon icon = createImageIcon("/logo.png","漂亮但无意义的拼音");

protected ImageIcon createImageIcon(String path,String description) { java.net.URL imgURL = getClass().getResource(路径); 如果(imgURL!= null){ 返回新的 ImageIcon(imgURL,描述); } 别的 { System.err.println("找不到文件:"+ path); } 返回空值; }

JLabel lblImgLogin = new JLabel(icon);

同样的问题,在 eclipse 上工作但在导出到可运行的 jar 文件时不工作

最佳答案

这个是正确的:

enter image description here

public class MainApp {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Testing");
        ImageIcon icon = createImageIcon("/resources/logo.png");
        JLabel label1 = new JLabel("Image and Text", icon, JLabel.CENTER);

        //Set the position of the text, relative to the icon:
        label1.setVerticalTextPosition(JLabel.BOTTOM);
        label1.setHorizontalTextPosition(JLabel.CENTER);

        frame.getContentPane().add(label1);
        frame.pack();
        frame.setVisible(true);
    }

    protected static ImageIcon createImageIcon(String path) {
        URL imgURL = MainApp.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
}

enter image description here

enter image description here

关于Java 项目在 Eclipse 上工作但在导出到可运行的 jar 文件时不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28452508/

相关文章:

java - 如果传递了错误类型的对象,我应该抛出什么类型的异常?

java - 调试:使用 System.out.println() 或不使用 System.out.println()

javascript - 我如何在eclipse中创建自动滑动图像的背景

java - android如何区分智能手机或平板电脑

java - Dart 可以运行 jar 归档吗?

java - 如何在所有操作系统上运行 .jar 文件并将输出保存到文件中?

java - 从同一流发送序列化对象和 byte[]

java - 双向 jpa hibernate 关系 @OneToMany @ManyToOne 失败,因为未存储父 ID

java - 修改 Spring 消息文本而不重新启动应用程序?

java - 我的 Java 程序如何在其 .jar 文件中存储文件?