英文:
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've been playing around with JButtons and I'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("/Apple.jpg");
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论