JavaFX卡牌展示程序启动异常排查求助
Let's break down what's causing this error and how to fix it quickly.
Root Cause
Looking at your stack trace, the critical error line is:
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
This happens because when you create a new Image() with a raw Windows file path like c:\Users\Desktop\Tempory\cardXX.png, JavaFX tries to parse this as a URL. The c: part is treated as a URL protocol (like http:// or file://), which isn't valid—hence the "unknown protocol" exception.
Fix 1: Use the file:// Protocol for Local Paths
Update your image path to include the proper file:// prefix for Windows. Note that Windows paths require three slashes after file: (to account for the drive letter):
// Replace every instance of your Image initialization with this corrected path format String imageUrl = "file:///c:/Users/Desktop/Tempory/card" + randomNumber + ".png"; ImageView imgViewCard = new ImageView(new Image(imageUrl));
Make sure to replace backslashes (\) with forward slashes (/) in the path—URLs use forward slashes regardless of the OS.
Fix 2: Use Classpath Resources (Better for Deployable Apps)
Hardcoding absolute paths is fragile (it breaks if you move the project or share it with others). A better approach is to put your card images in your project's resources directory (e.g., src/main/resources in a Maven/Gradle project), then load them using the class loader:
// This loads the image from the classpath, no hardcoded local paths needed ImageView imgViewCard = new ImageView(new Image(getClass().getResourceAsStream("/card" + randomNumber + ".png")));
Just ensure your card1.png to card54.png files are placed directly in the resources folder, and this will work everywhere—even when you package your app into a JAR.
Quick Checks to Avoid Future Issues
- Double-check that your image files exist at the specified path, with the correct filenames (e.g.,
card53.pngfor the first joker, no typos). - Verify your class name matches: Your code defines
public class JavaFXCards, but the error mentionsJavaFXCardGUI.start—make sure there's no mismatch here (rename the class or update references if needed).
内容的提问来源于stack exchange,提问作者Ramitha Silva

