Java中getClass().getResource()的参数路径应如何填写?
Hey Kevin, let's sort out this path problem together! I’ll break down how getClass().getResource() works and get your image loading correctly.
First, a key thing to understand: getResource() looks for files relative to your project's classpath (which in your case is the bin folder of your B-Tring project), not your Mac's system-level absolute path. That’s why the full system path you tried didn’t work—it’s not how the Java classloader locates resources.
The Correct Path to Use
Since your textures package (folder) lives inside the bin directory, here are two reliable options:
Absolute Classpath Path (Recommended)
Use a leading slash to start from the root of your classpath (thebinfolder):return new ImageIcon(getClass().getResource("/textures/Center_Ring_0.png"));This works no matter where the class calling this code is located in your package structure, so it’s the most stable choice.
Relative Path (Depends on Your Class’s Location)
If the class running this code is in the same root package level astextures(no nested sub-packages), you could also use:return new ImageIcon(getClass().getResource("textures/Center_Ring_0.png"));Just note that this will break if you move your class to a different nested package later.
Quick Validation Step
Make sure your image is actually being copied to the bin/textures folder:
- If
texturesis a package under yoursrcfolder, Eclipse should automatically copy the image tobin/textureswhen you build the project. - If
texturesis directly in your project root (not undersrc), right-click the folder → Build Path → Use as Source Folder so Eclipse copies its contents tobinduring builds.
That should get your ImageIcon loading successfully!
内容的提问来源于stack exchange,提问作者Kevin1031

