Netbeans 上的 Java 图像路径

发布于 2024-12-07 23:54:01 字数 412 浏览 6 评论 0原文

我正在爪哇冒险,所以我正在建造一艘扫雷舰。现在机制已经完成了,我想让它变得更加用户友好。

尝试将 ImageIcon 添加到所有按钮,但我做不到!我不知道Java是如何工作的!

我正在这样做:(

假设这是扩展一个 JButton)

super(new ImageIcon("/minesweeper/resources/bomb.png"));

这样的包:

  • minesweeperminesweeper.componentsminesweeper.resources
  • 我有
  • (试图在这里组织图像)
  • test(一些仅用于测试的东西)

我做错了吗? (ofc,但这怎么是对的呢?)

Im adventuring at Java so Im building a minesweeper. The mechanics are done now I want to make it some user friendly.

Tried to add an ImageIcon to a button on everyway but I cant do it! I dont know how Java works on this!

Im doing this:

(suppose this is extending a JButton)

super(new ImageIcon("/minesweeper/resources/bomb.png"));

I have packages like this:

  • minesweeper
  • minesweeper.components
  • minesweeper.resources (trying to organize images here)
  • test (some stuff for testing only)

Am I doing it wrong? (ofc, but how is it right?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔戏命师 2024-12-14 23:54:01

您可以通过以下方式获取图像:

new ImageIcon(getClass().getResource("/minesweeper/resources/bomb.png"))

检查 Java 文档 公共 URL getResource(String name)

You can get the images in this way:

new ImageIcon(getClass().getResource("/minesweeper/resources/bomb.png"))

Check the Java Doc for public URL getResource(String name)

好听的两个字的网名 2024-12-14 23:54:01

为了避免可能出现的任何问题,特别是在使用不同的打包方法时,请创建一个名为 res 之类的新包,然后在其中浸泡一个 Res.java 。将您的图像放在同一包目录中。现在,当您想要阅读某些内容时,您将使用 Res.getClass().getResourceAsStream("filename"); 获取 InputStream,然后使用以下命令创建一个新的 ImageIcon流(new ImageIcon(is))。这将为您提供一个可以与标签一起使用的ImageIcon

如果你想使用 super 构造函数来设置图像,你可以一次性完成:

super(new ImageIcon(Res.getClass().getResourceAsStream("filename")));

否则,只需使用setIcon(..);

编辑:您将使用现有的资源包。只需在其中放置一个 Res.java 即可。

To avoid any problems that may arise, especially when different packaging methods are used, make a new package called res or something, then dunk a Res.java in it. Put your images in the same package directory. Now, when you want to read something, you'll get the InputStream using Res.getClass().getResourceAsStream("filename");, then create a new ImageIcon with the stream (new ImageIcon(is)). This gives you an ImageIcon which you can use with the label.

If you want to use the super constructor for setting the image, you can do it in one go:

super(new ImageIcon(Res.getClass().getResourceAsStream("filename")));

Otherwise, just use setIcon(..);.

Edit: you'll use your existing resources package. Just put a Res.java in there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文