Adding/Loading java 中的图像
Adding/Loading an image in java
我正在尝试加载要在屏幕上显示的图像(只是想知道如何做)。
问题是当程序尝试加载 "apple.png"(保存在我的桌面上)时,它找不到图像 - 图像文件需要存储在哪里才能找到它们?这是我的加载方法:
private void loadImage() {
ImageIcon appleIcon = new ImageIcon("apple.png");
Image appleImage = appleIcon.getImage();
}
如果你想从桌面访问它,你应该使用完整路径。处理资源的最简单方法是在您的 java 项目中创建一个文件夹,您可以通过 "folderName/fileName.example".
访问该文件夹
如果只想使用文件名,文件路径("apple.png")是相对于源文件夹的。所以你必须把它放在那里。
您也可以使用桌面文件的绝对路径(类似 "C:\Users\your.name\Desktop" 的东西)
来自javadoc:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:
new ImageIcon("images/myImage.gif")
如@Shriram 所述,当您仅指定文件名(带扩展名)时,它将在当前目录中搜索该文件。
提示:存在一个以URL
作为参数的构造函数重载。
可以选择使用完整路径
C:\filefolder\file.jpg
尽管回答你的问题
无论您的 java 文件在哪里,它都会想到 "home is" 为自己创建一个 java 工作区,将您的 java 源文件放入其中,并在其中创建一个文件夹来放置任何资产你想要这样你就可以简单地调用 "apple.jpg"
我正在尝试加载要在屏幕上显示的图像(只是想知道如何做)。
问题是当程序尝试加载 "apple.png"(保存在我的桌面上)时,它找不到图像 - 图像文件需要存储在哪里才能找到它们?这是我的加载方法:
private void loadImage() {
ImageIcon appleIcon = new ImageIcon("apple.png");
Image appleImage = appleIcon.getImage();
}
如果你想从桌面访问它,你应该使用完整路径。处理资源的最简单方法是在您的 java 项目中创建一个文件夹,您可以通过 "folderName/fileName.example".
访问该文件夹如果只想使用文件名,文件路径("apple.png")是相对于源文件夹的。所以你必须把它放在那里。
您也可以使用桌面文件的绝对路径(类似 "C:\Users\your.name\Desktop" 的东西)
来自javadoc:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:
new ImageIcon("images/myImage.gif")
如@Shriram 所述,当您仅指定文件名(带扩展名)时,它将在当前目录中搜索该文件。
提示:存在一个以URL
作为参数的构造函数重载。
可以选择使用完整路径 C:\filefolder\file.jpg
尽管回答你的问题 无论您的 java 文件在哪里,它都会想到 "home is" 为自己创建一个 java 工作区,将您的 java 源文件放入其中,并在其中创建一个文件夹来放置任何资产你想要这样你就可以简单地调用 "apple.jpg"