你的图像文件必须位于哪个位置,以便以下代码可以正常工作?

huangapple 未分类评论45阅读模式
英文:

Where would my image file have to be located in order for the following code to work?

问题

window = new JFrame("Test");
window.setSize(1000, 600);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(null);

Icon icon = new ImageIcon("/Apple.jpg");
JButton apple = new JButton(icon);
apple.setBounds(50, 50, 200, 200);
window.add(apple);

我想知道 Apple.jpg 文件需要放在什么位置,以使得这段代码能够正常运行?目前,Apple.jpg 文件与这个类文件位于同一个包中。


<details>
<summary>英文:</summary>

So I&#39;ve been playing around with JButtons and I&#39;ve been trying to add an ImageIcon to a JButton. I have the following code:

window = new JFrame("Test");
window.setSize(1000, 600);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(null);

Icon icon = new ImageIcon("/Apple.jpg");
JButton apple = new JButton(icon);
apple.setBounds(50, 50, 200, 200);
window.add(apple);

I was wondering where would the Apple.jpg file have to be located for the code to work? Currently, Apple.jpg is located in the same package as this class.

</details>


# 答案1
**得分**: 0

查看构造函数`ImageIcon(String)`的源代码,我得出结论:传递的字符串会按原样处理。

因此,根据您在问题中发布的代码:
```java
Icon icon = new ImageIcon("/Apple.jpg");

Java将在根目录中搜索文件Apple.jpg

如果您在像我一样的Windows计算机上运行,Java会将我的根目录视为C:\(在我的计算机上),因此它会搜索此文件:C:\Apple.jpg

此评论链接的答案(来自Gilbert le Blanc)中详细介绍了加载图像的各种不同方式。我只是尝试回答您的问题。因此,使用您问题中的代码,对它的回答是您需要将文件(Apple.jpg)放在根目录中。我假设您知道在计算机上根目录的位置。无论如何,我在您的问题中找不到足够的信息来帮助您。例如,我无法确定您使用的平台是什么。

英文:

Looking at the source code for constructor ImageIcon(String), leads me to the conclusion that the string you pass is treated as is.

Hence, according to the code you posted in your question, i.e.

Icon icon = new ImageIcon(&quot;/Apple.jpg&quot;);

Java will search for file Apple.jpg in the root directory.

If you are running on a Windows machine, like I am, Java considers my root directory to be C:\ (on my machine) so it will search for this file: C:\Apple.jpg

The answer linked to in this comment to your question (from Gilbert le Blanc) details all the different ways to load an image. I just tried to answer your question. So using the code in your question, the answer to it is that you would have to place your file (Apple.jpg) in the root directory. I'm assuming that you know where that is on your computer. In any case, I couldn't find enough information in your question to help you with that. for example, I couldn't tell what platform you are on.

huangapple
  • 本文由 发表于 2020年4月3日 23:58:38
  • 转载请务必保留本文链接:https://java.coder-hub.com/61015802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定