【问题标题】:Runnable Jar File doesn't load resources可运行 Jar 文件不加载资源
【发布时间】:2020-02-14 17:42:50
【问题描述】:

在 IntelliJ 中我可以运行:

ImageIcon icon = new ImageIcon("src/de/therealjan/tools/pictures/pic.png");

但是在一个无法运行的可运行 JAR 文件中。 我已经尝试过“/pictures/pic.png”,但这也不起作用。

有什么想法吗?

【问题讨论】:

标签: java image swing jframe embedded-resource


【解决方案1】:

你应该在你的类路径或你的类路径中的目录中添加图像 然后像这样加载你的图片:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("src/de/therealjan/tools/pictures/pic.png");
ImageIcon icon = new ImageIcon(resource);

【讨论】:

  • 我写了URL url = getClass().getResource("src/de/therealjan/tools/pictures/pic.png"); ImageIcon img = new ImageIcon(url);,我得到了一个 NullPointerException?
  • 我添加了另一种您可以尝试的方法。但是你从哪里得到 NullPointer?不是getClass()吗?还是在下一行?
  • 第二种方法有效。我可以对像 txt 这样的每个文件都使用它吗?
  • @TheRealJan 试试de/therealjan/tools/pictures/pic.png
  • 我认为可以。最好的方法是尝试一下:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
相关资源
最近更新 更多